基于来自第三个的随机记录从第二个表加入

时间:2013-07-30 17:58:28

标签: mysql

table1>画廊|每个都由一个不同的身份识别

table2>图片|图库中的图像

table3> 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'

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

2 个答案:

答案 0 :(得分: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
)

答案 1 :(得分:0)

您可以通过联接链接表。我不像使用t-sql那样熟悉mysql,但以下内容至少可以让你接近。

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