返回仅具有一个特定多对多关系的记录

时间:2016-02-18 19:59:40

标签: mysql mysqli

鉴于此结构

CREATE TABLE locations
    (`id` int, `Name` varchar(128))
;

INSERT INTO locations
    (`id`, `Name`)
VALUES
    (1, 'Location 1'),
    (2, 'Location 2'),
    (3, 'Location 3')
;

CREATE TABLE locations_publications
    (`id` int, `publication_id` int, `location_id` int)
;

INSERT INTO locations_publications
    (`id`, `publication_id`, `location_id`)
VALUES
    (1, 1, 1),
    (2, 2, 1),
    (3, 2, 2),
    (4, 1, 3)
;

我想根据与publication_id = 2只有一个关系这一事实,只找到位置2。

由于它有两个关系行,它不应该返回位置一。

这是我正在寻找的东西,但当然dosnt有效,因为它限制了与publication_id = 2的关系。

select * from locations
join locations_publications on locations_publications.location_id = locations.id
where locations_publications.publication_id = 2
group by (locations.location_id)
having count(*) = 1

1 个答案:

答案 0 :(得分:1)

您可以通过聚合执行此操作:

select location_id
from locations_publications
group by location_id
having count(*) = 1

如果某个位置可能包含多个具有相同发布的记录,请将having条件更改为count(distinct publication_id) = 1

根据您的编辑,您可以使用条件聚合:

select location_id
from locations_publications
group by location_id
having count(*) = sum(case when publication_id = 2 then 1 else 0 end)