SQL连接子句返回具有多个匹配项的行而不进行分组

时间:2012-11-06 10:00:07

标签: mysql sql

我想从JOIN查询中提取多次出现的记录,但不会将它们分组。

示例表:

tbl_names
id    Name
1     Mark
2     John
3     Jane
4     Paul

tbl_locations
id    Location
1     Berlin
2     Frankfurt
2     Stockholm
3     Helsinki
3     Madrid
3     London
4     Paris

ID是外键。

现在,查询的结果将是:

id     Name    Location
2      John    Frankfurt
2      John    Stockholm
3      Jane    Helsinki
3      Jane    Madrid
3      Jane    London

即。所有JOIN记录,其中第一个表中的记录在JOIN子句结果中出现多次。

我可以把它归为一组:

SELECT tbl_names.id, tbl_names.Name, tbl_locations.Location FROM tbl_names
 INNER JOIN tbl_locations ON (tbl_names.id = tbl_locations.id)
 GROUP BY tbl_names.id
 HAVING COUNT(tbl_names.id) > 1

我想要的是让它们不被分组。我尝试了一个子条款和NOT IN,但它非常慢,并没有给我我想要的结果。

欢迎任何启示。

1 个答案:

答案 0 :(得分:4)

使用这个:

SELECT tbl_names.id, tbl_names.Name, tbl_locations.Location
FROM tbl_names
INNER JOIN tbl_locations ON (tbl_names.id = tbl_locations.id)
where tbl_names.id in (select id from tbl_locations
                       group by id having count(*) > 1);

此选择显示您已有的联接,但仅选择名称/ ID,其在位置表中具有多个条目。

根据https://stackoverflow.com/a/3520552/1741542,这可能比普通子查询更快:

create view view_id_locations as
    select id
    from tbl_locations
    group by id
    having count(*) > 1;

SELECT tbl_names.id, tbl_names.Name, tbl_locations.Location
FROM tbl_names
INNER JOIN tbl_locations ON tbl_names.id = tbl_locations.id
inner join view_id_locations on tbl_names.id = view_id_locations.id;