MYSQL 查询优化 - 如何从连接的右表中获取唯一列

标签 mysql sql

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/

相关文章:

mysql - 针对同一张表的不同条件获取不同的计数

MySQL:有什么办法可以将这N个查询变成更少的查询吗?

sql - PL/SQL 匿名 block 'Exact fetch returns more than requested number of rows'

mysql - Doctrine 1 选择具有重复值的列

sql - mySQL 递归计数()

php - 根据其他列表显示数据库中的数据 Laravel 5

php - 如何对表的行进行排序?

MySQL表设计: Primary Foreign Multi-Column Key possible?

sql - where 子句中的连接字符串是否可 SARGable?

带有 OR 子句和只有一个参数的 SQL 查询