加入一对多 - 显示每个外键的多个表中的第一行

时间:2013-05-31 14:22:30

标签: mysql

我想使用以下查询从图库中获取前5行,但我想只从每行_gallery_gallery_items获得第一个匹配。

所以,例如,我想从画廊获取狗画廊,猫画廊和后续画廊标题,但我只想从_gallery_gallery_items获得第一场比赛,其中_gallery_gallery_items.gallery_id = gallery.id。

所以结果应该是这样的:

id = 1
title = dog gallery
gallery_item_id = 70

id = 2
title = cat gallery
gallery_item_id = 102

id = 3
title = mouse gallery
gallery_item_id = 500

狗狗画廊不应出现后续的gallery_item_ids,例如。 72,72

到目前为止,这是我的查询:

SELECT gallery.id, gallery.title, _gallery_gallery_items.gallery_item_id
FROM gallery LEFT JOIN
_gallery_gallery_items ON gallery.id = _gallery_gallery_items.gallery_id

表格:

id|title
1 |dog gallery
2 |cat gallery
3 |mouse gallery

_gallery_gallery_items

id|gallery_id|gallery_item_id
1|     1     |      70
2|     2     |      102
3|     1     |      71
4|     1     |      72
5|     3     |     500

4 个答案:

答案 0 :(得分:2)

我认为您可以使用MAX()GROUP BY聚合函数

来实现此目的

对于最后一个图库item_id

SELECT a.id, a.title, MAX(b.gallery_item_id)
FROM gallery a
LEFT JOIN _gallery_gallery_items b 
ON a.id = b.gallery_id
GROUP BY b.gallery_id

对于第一个图库item_id

SELECT a.id, a.title, MIN(b.gallery_item_id)
FROM gallery a
LEFT JOIN _gallery_gallery_items b 
ON a.id = b.gallery_id
GROUP BY b.gallery_id, a.title

答案 1 :(得分:0)

试试这个:

SELECT
    g.id,
    g.title,
    (
        SELECT 
            gallery_item_id
        FROM
            _gallery_gallery_items gi
        WHERE 
            gi.gallery_id = g.id
        ORDER BY
            id
        LIMIT 1
    ) as gallery_item_id
FROM 
    gallery g

答案 2 :(得分:0)

像这样它应该有效:

SELECT
  g.id,
  g.title,
  ggi.gallery_item_id
FROM gallery AS g
JOIN (
    SELECT 
      gallery_id, 
      MIN(gallery_item_id) 
    FROM _gallery_gallery_items 
    GROUP BY gallery_id
) AS ggi ON ggi.gallery_id = g.id

答案 3 :(得分:0)

假设您有表A和一对多关系表AB,许多表是B:

Select *
From A table_a
Left Join (select * from AB group by A_id) table_ab on table_ab.A_id = table_a.id
#... (rest is yours)

感谢。