从外表中只找到一行与另一个表

时间:2013-08-31 15:30:32

标签: sql sql-server

我有2个表库(Gallery_ID,Name)和Gallery_Image(ID,Gallery_ID,Image)。我的问题是我想只选择每个图库的一个图像

我试过这个查询

SELECT distinct  top 1  Gallery.Gallery_ID, Gallery.Gallery_Name,Gallery.Gallery_Name  as Gallery_Image
FROM         Gallery 
    union
select distinct Gallery_Image.Gallery_ID,Gallery_Image.Gallery_Images as Gallery_Name,Gallery_Image.Gallery_Images
from Gallery_Image inner join Gallery on Gallery.Gallery_ID=Gallery_Image.Gallery_ID
where Gallery_Image.Gallery_ID in(select Gallery_ID from Gallery)

1 个答案:

答案 0 :(得分:1)

你说:“我想只选择每个画廊的一张图片。”这是有道理的。我不知道你的查询是如何与这个问题相关的。

您没有指定您正在使用的数据库。一种好方法是使用row_number()为图库中的图像分配顺序。关键是要做一个随机排序。最后一块取决于数据库。这是SQL Server语法:

select gi.*
from (select gi.*, row_number() over (partition by Gallery_Id order by newid()) as seqnum
      from Gallery_Image gi
     ) gi
where seqnum = 1;

编辑:

要从Gallery表中获取信息,请将其加入:

select gi.*
from (select gi.*, row_number() over (partition by Gallery_Id order by newid()) as seqnum
      from Gallery_Image gi
     ) gi join
     Gallery g
     on gi.Gallery_Id = g.Gallery_Id and
        seqnum = 1;

我还移动了逻辑,将“第一”图像从on子句中带到where子句。