如何在以下场景中获取记录

时间:2011-12-22 06:53:51

标签: mysql sql-match-all

我有一张如下表:

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

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

例如,给定术语名称 physics&数学我的输出应该如下

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

ID设置001也包含chemistry,这就是不应该包含它的原因。

3 个答案:

答案 0 :(得分:1)

您的问题:获取所有没有其他行具有相同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'))

答案 1 :(得分:0)

首先,您需要解析查询以转换'&amp;'到SQL'OR'运算符 用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 :(得分:0)

一种可能的方法:

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