Person
id | name
1 | Mark
2 | John
3 | Cathy
4 | Susan
5 | Rick
Property
id | property_type (A,B,C,D,E,F)
1 | A
1 | B
1 | C
2 | A
2 | A
2 | A
3 | C
4 | D
4 | E
4 | F
4 | A
3 | A
5 | A
5 | A
Query would be - Find out people's id and name who owns property of only Type A. Answer should be John and Rick
Right now, I am doing it this way
select distinct(p.id), p.name
from
Person p
INNER JOIN Property t
ON p.id = t.id
WHERE t.property_type = 'A'
AND p.id NOT IN (
SELECT
id
from
Property
where property_type IN (
'B','C','D','E','F'
)
)
order by p.id desc
表有十万行,这就是我尝试优化此查询的原因。
我打算以这种方式获取结果,找出只有 A 类属性的人。
感谢任何帮助。
最佳答案
您可以在having
子句中使用条件聚合:
select pers.id,
pers.name
from person pers
join property prop
on pers.id = prop.id
group by pers.id,
pers.name
having sum(case when prop.property_type = 'A' then 1 else 0 end) >= 1
and sum(case when prop.property_type <> 'A' then 1 else 0 end) = 0
fiddle : http://sqlfiddle.com/#!9/a3720/1/0
(我想你指的是约翰和瑞克)
关于MYSQL 查询优化 - 如何从连接的右表中获取唯一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29405642/