2013-08-26 91 views
2

我是mysql的新手。這裏是我的db表的結構。*我怎樣才能加入所有三個表,使結果看起來像第四個表?sql join三個表的查詢問題

表產品

id  name category user_id 
1  abc  2    1 
2  syz  3    1 

表格類別

id  name 
1  aaa 
2  bbb 
3  ccc 

表product_image

id  image  product_id 
1  abc.jpg   1 
2  xyz.jpg   1 

第四表結果看起來像

id  name  category_name   image 
1  abc  aaa     xyz.jpg 

請幫我解決這個問題。我試過但沒有得到正確的結果。

SELECT product. * , categories.name AS cat_name, product_image.image AS product_image 
FROM `product` 
INNER JOIN categories ON categories.id = product.category and `user_id`='1' 
INNER JOIN `product_image` ON product_image.product_id = product.id 
ORDER BY rand() 
LIMIT 1 

編輯零件

我們需要product_image一個圖像這是在按照相關的多個圖像的product_id

+2

你想要什麼結果? –

回答

0
SELECT 
    p.id, p.name, p.category, p.user_id, 
    c.id, c.name as cat_name, 
    prod_image.image as product_image 
FROM 
    Product p, 
    Categories c, 
    product_image prod_image 
WHERE 
    p.user_id=1 
AND 
    p.category=c.id 
AND 
    prod_image.product_id=p.id 
ORDER BY rand() LIMIT 1 
+0

謝謝!!我們需要根據product_id –

+0

將多個圖像相關聯的product_image的多個圖像中的一個圖像提供給您。 – 2013-08-26 10:55:06

+0

確定只是編輯我的問題 –

0

試試這個

SELECT product.name , categories.name AS cat_name, product_image.image AS product_image 
FROM `product` 
JOIN categories ON (categories.id = product.category) 
JOIN `product_image` ON product_image.product_id = product.id Where product.`user_id`='1' 
ORDER BY rand() 
LIMIT 1 
+0

謝謝!!我們需要根據product_id –

0
SELECT Product.id as Id,Product.name as name, Categories.name as category_name ,product_image.image as image 
FROM 
Product, Categories,product_image 
WHERE 
Product.ID='1' AND Categories.Id='1' AND product_image='1' 
+0

感謝關聯多個圖像的來自product_image的多個圖像中的一個圖像!我們需要根據product_id –

5

試試這個

SELECT p.id, p.name , c.name as category_name, i.image FROM Product AS p 

INNER JOIN Categories as c 

ON c.id=p.category LEFT JOIN 

(SELECT image, product_id FROM product_image ORDER BY RAND() LIMIT 1 ) AS i ON i.product_id=p.id WHERE p.id=1 
+0

將多個圖像關聯的product_image的多個圖像中的一個圖像如果這適用於您,請將其標記爲正確 – KTAnj