2011-12-22 126 views
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 

标识设置001还包含chemistry这就是为什么它不应该被包括在内。

+1

你能解释一下为什么你的结果不会在你的例子中包括'test1 001 physics'和'test1 001 maths'?它们都与其他两行匹配的“物理”和“数学”相匹配。有什么不同? – ChrisWue 2011-12-22 07:00:37

+0

@ChrisWue,因为'id 001'也包含'chemistry' – rabudde 2011-12-22 07:03:53

回答

0

首先你需要分析你的查询到 '&' 到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'); 

则: 使用左旋

"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 
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')) 
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