2013-07-30 78 views
0

table1> galleries |每個由不同的編號標識從第二張表中根據第三張隨機記錄加入

table2> images |圖庫內的圖像

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' 

如何將這些組合成一個查詢?

回答

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 
) 
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 
相關問題