【问题标题】:how to get records in the following scenario以下场景如何获取记录
【发布时间】:2012-01-25 21:17:19
【问题描述】:

我有一张如下表:

node_name              id            term_name
----------------------------------------------
test1                  001           physics 
test1                  001           maths    
test1                  001           chemistry    
test2                  002           physics    
test2                  002           maths

给定术语名称的组合,我想查找 id 集仅包含给定术语名称的所有行。

例如,给定术语名称physics & maths,我的输出应该如下所示

node_name              id            term_name
----------------------------------------------
test2                  002           physics   
test2                  002           maths

ID 集 001 还包含 chemistry,因此不应包含它。

【问题讨论】:

  • 你能解释一下为什么你的结果在你的例子中不包括test1 001 physicstest1 001 maths吗?它们都匹配physicsmaths,与其他两行匹配的方式相同。有什么区别?
  • @ChrisWue 因为id 001 还包含chemistry

标签: mysql sql-match-all


【解决方案1】:

首先,您需要解析查询以将“&”转换为 SQL 的“或”运算符 在 PHP 中:

//Parse the query
        $arr = explode('&',$query);
    $where = '';
//get the term count
    $count = count($arr);
    foreach($arr as $value){
    $where .= "term_name = '" . $value . "' OR";
    }
    //Remove last or
    $where = rtrim($where,'OR');

然后: 使用L

"select node_name ,count(1) as Total from my table where $where
group by node_name
having Total =" . $count

最后:

您的查询必须采用以下格式:

select x,count(1) as total from mytable where field1 = 'term1' or field1 = 'term2' having total = 2

【讨论】:

    【解决方案2】:

    您的问题:获取不存在具有相同 ID 但其他 term_names 的其他行的所有行

    SELECT * FROM <table> x WHERE
      term_name IN ('physics','maths') AND
      NOT EXISTS (SELECT * FROM <table> WHERE id=x.id AND term_name NOT IN ('physics','maths'))
    

    【讨论】:

      【解决方案3】:

      一种可能的方法:

      select id, node_name 
      from nodes join 
        (select id, 
             count(*) 
      from nodes
        where node_name in ('physics','math')
      group by id
      having count(*) = 2 // this is set when generating the query ) as eligible_nodes
        on nodes.id = eligible_nodes.id
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-23
        相关资源
        最近更新 更多