想找出只有一个作者写的 book_id 和 p_id=1

want to find out the book_id which is written by a single author only and p_id=1

我有 3 个 table。

这是人 table:

这是汽车 table:

这是 Person_car table 多对多 hloding 连接列:

现在我想找出属于一个人的c_id(车号)和p_id=1.

这意味着在这种情况下我应该得到 c_id 因为 100 bcs c_id 200 属于 p_id 1 和 2

请帮我写 sql 查询。

您可以使用聚合:

select c_id
from person_car
group by c_id
having count(*) = 2                                      -- owned by 2 persons
   and max(case when p_id = 100 then 1 else 0 end) = 1   -- including p_id 100

在MySQL中,我们可以将最后一个条件缩短为:

and max(p_id = 100) = 1

看了你的问题,我知道你想找到只有一个人拥有的汽车/,p_id = 1 只是一个例子/。如果是这种情况,请尝试:

select
   c.id as car_id,
   c.color as car_color,
   c.model as car_model,
   p.id as person_id,
   p.first_name || ' ' || p.last_naem as person_name,
from
   car c
   join person_car pc on (pc.c_id = c.id)
   join pesron p on (p.id = pc.p_id)
where
   c.id in (select c_id from peson_car group by c_id having count(1) = 1)

谢谢。