[英]SQL selecting rows with matching values
我正在尝试使用php和sql组合一个SELECT语句,但我很难尝试选择我想要的项目。
让我说我的桌子看起来像这样......
master_record_id credit_id credit_value
118 5 Brian J
119 5 Brian J
120 7 Katie W
121 5 Brian J
121 7 Katie W
125 7 Katie W
我正在尝试找到哪个master_record_id
同时包含Katie W和Brian J. 所以我选择了credit_value = Brian J OR Katie W
,这就是结果。
基于这个小选择,我可以看到我想要的答案是121
但我该如何选择呢? 我想找到包含Katie W和Brian J的master_record_id
......
有没有办法让我说,“选择包含Katie W和Brian J的master_record_id”?
您需要使用自联接 :
SELECT a.master_record_id
FROM tablename a JOIN tablename b USING (master_record_id)
WHERE a.credit_value = 'Brian J'
AND b.credit_value = 'Katie W'
select master_record_id
from your_table
where credit_value in ('Brian J', 'Katie W')
group by master_record_id
having count(distinct credit_value) = 2
YOou必须调整在价值having
你在子句中值的数量in
条款。
由于性能的原因,这不是最好的方法,但无论如何它应该工作:
select master_record_id, credit_id, credit_value
from your_table
where master_record_id in (
select master_record_id from your_table where credit_value = 'Brian J')
and master_record_id in (
select master_record_id from your_table where credit_value = 'Katie W')
它将返回所有包含Katie W和Brian J的master_record_id记录
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.