Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 在“外文”中仅从表中查找一行,并查找其他表_Sql_Sql Server - Fatal编程技术网

Sql 在“外文”中仅从表中查找一行,并查找其他表

Sql 在“外文”中仅从表中查找一行,并查找其他表,sql,sql-server,Sql,Sql Server,我有两张桌子图库(图库ID,名称)和图库图像(ID,图库ID,图像)。我的问题是我只想选择每个画廊的一个图像 我试过这个问题 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_Im

我有两张桌子图库(图库ID,名称)和图库图像(ID,图库ID,图像)。我的问题是我只想选择每个画廊的一个图像

我试过这个问题

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)
你说:“我只想选择每个画廊的一张图片。”这是有道理的。我不知道你的问题与这个问题有什么关系

您不指定正在使用的数据库。一种很好的方法是使用
row\u 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;
编辑:

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

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;

我还将逻辑从
where
子句移动到
on
子句中的
上的“第一个”图像。

@SunnySandeep。如果我正确地解释了问题,那么解决方案适用于该数据库。我还想选择库名。请帮助我。我使用的是sql server 2008