我正在尝试为MySQL编写一个查询,该查询选择所有有子记录的父条件。我的模式比这个更复杂,但这就是我的想法。
例如:
parent_table:
id
child_table
parent_id,id,key,value
所以,
SELECT pt.id FROM parent_table pt
JOIN child_table ct ON pt.id = ct.parent_id
WHERE **AllOfTheseExist** (ct.key = "keyName1" AND ct.value = "value1")
AND (ct.key = "keyName2" AND ct.value = "value2")
如果我或他们在一起,效果很好,但我需要它是排他性的,而不是包容性的。
查询的问题是ct.key不能同时等于同一行中的keyname1和keyname2。您需要多次检查子表,或者使用条件聚合。这里有一个使用exists
:的选项
SELECT id
FROM parent_table pt
WHERE EXISTS (
SELECT 1
FROM child_table ct
WHERE pt.id = ct.parent_id
AND ct.key = 'keyName1'
AND ct.value = 'value1') AND EXISTS (
SELECT 1
FROM child_table ct
WHERE pt.id = ct.parent_id
ct.key = 'keyName2' AND
ct.value = 'value2')
或者您可以使用条件聚合:
select id
from parent_table pt
where exists (
select 1
from child_table ct
where pt.id = ct.parent_id
group by ct.parent_id
having sum(case when ct.key = 'keyname1' and ct.value = 'value1'
then 1 else 0 end) > 0 and
sum(case when ct.key = 'keyname2' and ct.value = 'value2'
then 1 else 0 end) > 0 )
也许还有一个使用distinct
和多个joins
:的选项
select distinct pt.id
from parent_table pt
join child_table ct1 on pt.id = ct1.parent_id and
ct1.key = 'keyname1' and
ct1.value = 'value1'
join child_table ct2 on pt.id = ct2.parent_id and
ct2.key = 'keyname1' and
ct2.value = 'value1'