mysql SQL多表按单个字段计数

vulvrdjw  于 2023-05-28  发布在  Mysql
关注(0)|答案(2)|浏览(143)

MySQL / MariaDB结构:

| id |
|----|
| 1  |
| 2  |
| 3  |
Car
| person_id | car   |
|-----------|-------|
| 1         | Ford  |
| 2         | Mazda |
| 3         | Ford  |
| 3         | Mazda |
| 3         | BMW   |

什么查询可以得到正好有1辆车的人,而且车不是马自达?
期望的输出是个人ID 1。
注意事项:
如果使用GROUP BY,则查询应该是完整的group by,否则会出现以下错误,并且不希望更改SQL配置。
“在没有GROUP BY的聚合查询中,SELECT列表的表达式#1包含非聚合列'X';这与sql_mode=only_full_group_by不兼容”

cetgtptt

cetgtptt1#

您可以使用聚合和having来过滤:

select person_id
from car
group by person_id
having count(*) = 1              -- has just one car
   and max(car = 'Mazda') = 0    -- which is not a Mazda

我们可以直接从car表中获得结果。如果出于某种原因,需要从person中取出相应的行,我们可以join

select p.*
from person p
inner join (
    select person_id
    from car
    group by person_id
    having count(*) = 1 and max(car = 'Mazda') = 0
) c on c.person_id = p.id
oogrdqng

oogrdqng2#

另一种选择是,在相关子查询上使用EXISTS运算符的否定,如下所示:

select * -- you may replace * with your columns list
from Car t1 
where car <> 'Mazda' and
  not exists(
  select 1 from Car t2 
  where t1.person_id = t2.person_id and
        t1.car <> t2.car)

demo

相关问题