0

table1 > 画廊 | 每个都由不同的 id 标识

table2 > 图片 | 画廊中的图像

表 3 > galImgLink | 每条记录都将图像链接到图库

select 
  galId,
  galName 
from 
  galleries 
limit 
  0, 10

通过从链接表中选择随机记录,将图像连接到上面选择的每个记录

select 
   lnkImgId 
from 
   galImgLink 
where 
    lnkGalId = galId 
ORDER BY 
  RAND() 
LIMIT 
  0, 1

然后从图像表中获取相关图像

select 
  imgFile,
  imgTitle
from 
  Images 
where 
  imgId = lnkImgId and
  imgStatus = 'active'

我如何将这些组合成一个查询?

4

2 回答 2

0

我相信类似以下的方法会起作用:

SELECT galleries.galId, galleries.galName, Images.imgFile
FROM galleries
JOIN Images
ON Images.imgId = (
    SELECT lnkImgId
    FROM galImgLink
    WHERE lnkGalId = galleries.galId
    ORDER BY RAND()
    LIMIT 1
)
于 2013-07-30T18:11:45.460 回答
0

您可以通过连接链接表。我对 mysql 的熟悉不如对 t-sql 的熟悉,但以下内容至少应该能让你接近。

select Images.imgFile, galImgLink.lnkImgId, galleries.galId, galleries.galName
from Images
inner join galImgLink on Images.imgId = galImgLink.lnkImgId
inner join galleries on galImgLink.linkGalId = galleries.galId
limit 0, 10

进一步查看您的帖子,您似乎想要抓取 10 个画廊,每个画廊有 1 张随机图像,因此您可能需要一个相关的子查询:

select galleries.galId, galleries.galName,
(
select Images.imgFile
from Images
inner join galImgLink on Images.imgId = galImgLink.lnkImageId
where galImgLink.galId = galleries.galId
order by rand()
limit 0, 1
) as imgFile
from galleries
limit 0, 10
于 2013-07-30T18:13:58.230 回答