1

我想使用以下查询从图库中获取前 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

4 回答 4

2

MAX()我认为您可以使用和GROUP BY聚合功能来实现这一点

对于最后一个 gallery_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

对于第一个 gallery_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
于 2013-05-31T14:29:30.870 回答
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
于 2013-05-31T14:30:34.107 回答
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
于 2013-05-31T14:33:57.070 回答
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)

谢谢。

于 2016-06-10T11:16:31.123 回答