2

我有一张如下表:

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

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

例如,给定术语名称物理和数学,我的输出应该如下所示

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

Id set 001contains 也是chemistry为什么它不应该被包括在内的原因。

4

3 回答 3

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'))
于 2011-12-22T07:07:57.430 回答
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
于 2011-12-22T14:31:26.060 回答
0

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

//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
于 2011-12-22T07:07:37.270 回答