订购后选择一条记录

时间:2012-12-28 19:04:28

标签: mysql sql-order-by

我有一堆含有一堆艺术品的CD。我想在网页上显示每张CD的拇指图像,为此我需要从该CD中存在的许多艺术作品中选择一张图片...

查询选择所有艺术作品并按位置分组并想要选择第一个。在我订购之后,我不知道如何为每个记录选择第一张图片...

查询如下:

SELECT release_artwork.release_id, release_artwork.position, artwork.small_filename, artwork.small_width, artwork.small_height
FROM release_artwork
JOIN artwork ON artwork.artwork_id = release_artwork.artwork_id
ORDER BY release_artwork.position

enter image description here

3 个答案:

答案 0 :(得分:4)

我没有方便的MySQL实例,但是这应该有效 - 只需定义一个内联表来保存最小值,然后加入到它。

SELECT release_artwork.release_id, release_artwork.position, artwork.small_filename, artwork.small_width, artwork.small_height
FROM
  release_artwork
  inner JOIN artwork ON artwork.artwork_id = release_artwork.artwork_id
  inner join
  (
  SELECT
    ra.release_id as release_id
   ,min(ra.position) as rap
  FROM
    release_artwork ra
  group by
    ra.release_id
  ) mins
  on mins.release_id = release_artwork.release_id
    and mins.rap = release_artwork.position
ORDER BY
  release_artwork.release_id

答案 1 :(得分:2)

在这种情况下,您可以使用LIMIT 1将检索的结果限制为第一个。

答案 2 :(得分:0)

SELECT release_artwork.release_id, release_artwork.position, artwork.small_filename, artwork.small_width, artwork.small_height
FROM release_artwork
JOIN artwork ON artwork.artwork_id = release_artwork.artwork_id
ORDER BY release_artwork.position LIMIT 1

在末尾添加LIMIT 1会将其限制为单个结果。