3

我在一个名为的表中有这些值galley_images

id    gallery_id    image_id
1             1            1
2             1            2
3             1            3
4             2            4 
5             2            5 
6             2            6 
7             2            7
8             3            8

我想返回这样的结果:

id    gallery_id    image_id
1             1            1
4             2            4
8             3            8

基本上我只想要任何具有唯一性的记录的第一个实例gallery_id

我有一个使用 Access DB 的解决方案,但需要一个 MySQL 解决方案,Access 解决方案是:

SELECT id, First(gallery_id) AS FirstOfgallery_id,  
           First(image_id) AS FirstOfimage_id
FROM galley_images 
GROUP BY id

有什么帮助吗?

4

4 回答 4

2

The idea behind the subquery is to select the minimum ID for each gallery_ID. Then join it against itself to get all the columns of the table (if any).

SELECT  a.*
FROM    gallery_images a
        INNER JOIN
        (
            SELECT gallery_ID, MIN(image_ID) minID
            FROM gallery_images 
            GROUP BY gallery_ID
        ) b
            ON a.gallery_ID = b.gallery_ID AND
                a.image_ID = b.minID
于 2012-10-31T05:50:51.057 回答
1

try this:

    SELECT * 
  FROM   galley_images t
  JOIN 
       ( SELECT gallery_id,
                MIN(image_id) as image_id
         FROM   galley_images
         GROUP BY gallery_id )a
  ON   t.gallery_id    =a.gallery_id    
  AND  t.image_id=a.image_id


SQL Fiddle Demo

于 2012-10-31T05:50:19.973 回答
1
SELECT id, gallery_id, image_id FROM galley_images WHERE id IN (
        SELECT MIN(ID) 
        FROM gallery_images 
        GROUP BY gallery_ID
    )
于 2012-10-31T05:51:27.983 回答
1

John Woo 解决方案的一些补充:

SELECT  a.*
FROM    gallery_images a
    INNER JOIN
    (
        SELECT gallery_ID, MIN(id) id
        FROM gallery_images 
        GROUP BY gallery_ID
    ) b
        ON a.gallery_ID = b.gallery_ID AND
            a.id = b.id

我们必须通过最小记录 id 而不是通过 min(image_id) 获得,因为 image_id 可以以不同的顺序出现。

于 2012-10-31T06:33:18.557 回答