2015-06-26 90 views
0

我有關於從相同的兩個表中加入多個數據的問題。如何從相同的兩個表中加入多個記錄

第一個表被稱爲imagedata,它包含以下幾列:

ID|image_blob|mimetype|image_UUID 

第二個表稱爲price_history,它包含以下幾列:

price1|price2|image_name_homePage|image_name_loginPage|image_name_footer 

我試圖拉是來自imagedata表的image_blob表 其中

imagedata.ID=price_history.image_name_homePage 

,並在那裏

imagedata.ID=price_history.image_name_loginPage 

,並在那裏

imagedata.ID=price_history.image_name_footer 

基本上,我想實現的是,將顯示從imagedata其中imagedata.id等於price_history."price_history.image_*" 所有圖像斑點結果我似乎無法做到。我得到一個空的結果。 這裏是我當前的查詢:

SELECT 
    imagedata.`image_blob` as "blobA", 
    imagedata.`image_blob` as "blobB", 
    imagedata.`image_blob` as "blobC", 
FROM 
    imagedata 
    JOIN price_history AS price_historyA ON imagedata.`ID`=price_historyA.`image_name_homePage` 
    JOIN price_history AS price_historyB ON imagedata.`ID`=price_historyB.`image_name_loginPage` 
    JOIN price_history AS price_historyC ON imagedata.`ID`=price_historyB.`image_name_footer` 
+0

可以顯示示例數據和預期結果,或者更好地提供sqlfiddle。 – Jens

+0

'price_historyC'的JOIN指'price_historyB',這可能是您的問題。 – Jim

回答

0

您所查詢的是接近,但你需要如下加入imagedata表多次的東西,請注意其使用left join,而不是內部聯接,這樣,如果一些圖像值上缺少price_history您仍然可以獲得其他可用圖像的結果。如果你的數據庫是這樣的,它總是有price_history對所有數據的所有圖像和相應的項目將在imagedata那麼你可以只用join代替left join

select 
img1.image_blob as blobA, 
img2.image_blob as blobB, 
img3.image_blob as blobC, 
from price_history ph 
left join imagedata img1 on img1.id = ph.image_name_homePage 
left join imagedata img2 on img2.id = ph.image_name_loginPage 
left join imagedata img3 on img3.id = ph.image_name_footer 
+0

謝謝!它做到了!如果我想從第三個產品表中添加更多數據,比如product_name和product_updated,我可以加入嗎?產品具有'prouductID',相當於'price_history'中的'prouductID' – necross

+0

我已經上傳了幾個截圖來顯示問題。 – necross

0

你應該嘗試:

SELECT 
    imagedata.`ID`, 
    imagedata.`image_blob` 
FROM 
    imagedata 
JOIN price_history AS price_historyA ON imagedata.`ID`=price_historyA.`image_name_homePage` 
AND imagedata.`ID`=price_historyA.`image_name_loginPage` 
AND imagedata.`ID`=price_historyA.`image_name_footer` 

如果你想要的是,所有這三個列等於imagedata.ID

我上傳的截圖顯示的問題: enter image description here enter image description here

相關問題