1

I have two tables, Article and Image with one-to-many where Article is the parent and the Image has foreign key column article_id. Each Image also has the column position that is integer.

Now what I need is to I get all of the articles, regardless if there are any images for all of them, but for those that have one ore more images it needs to return a single image which has the lowest position stored in position column.

In other words along the pseudo lines:

SELECT FROM ALL ARTICLES LEFT JOIN IMAGES (WHERE IMAGE FOR THIS ARTICLE HAS SMALLEST POSITION)

What SQL query to get the above?

4

2 回答 2

0

One cannot give a precise answer without knowing your schema, but in essence you want to get the groupwise minimum:

SELECT *
FROM   Article LEFT JOIN (
         Images NATURAL JOIN (
           SELECT   article_id, MIN(position) AS position
           FROM     Images
           GROUP BY article_id
         ) AS t
       ) USING (article_id)
于 2013-10-24T18:47:41.727 回答
0
SELECT * FROM ARTICLES AS art
LEFT JOIN
 (SELECT article_id, image_id,
                 MIN(Position) AS Position
   FROM Images
   GROUP BY article_id, image_id) AS MinPos
 LEFT JOIN Images AS img ON
MinPos.article_id = img.article_id AND
MinPos.image_id = img.image_id
于 2013-10-24T18:57:01.527 回答