2016-07-02 96 views
0

我有兩張表,分別是propertiesproperty_images。在性能和property_images表中的字段如下MySQL查詢獲取所有照片

性能

property_id 
name 
address 
city 
type 

property_images

prop_img_id 
photoname 
property_id 

我有一個查詢獲得的兩個表的結果。但是當我運行查詢時,每個屬性只有一個圖像。但是我得到正確的圖像數量。我想獲取查詢中某個媒體資源的所有照片。查詢我的是這樣的:

SELECT *, photo, COUNT(property_photo.photo) as photocount 
FROM properties LEFT JOIN 
    property_photo 
    ON properties.property_id = property_photo.property_id 
GROUP BY properties.property_id 
LIMIT 6 

回答

0

您可以使用GROUP_CONCAT()

SELECT p.*, COUNT(pp.photoname) as photocount, 
     GROUP_CONCAT(pp.photoname SEPARATOR '|') 
FROM properties p LEFT JOIN 
    property_photo pp 
    ON p.property_id = pp.property_id 
GROUP BY p.property_id 
LIMIT 6; 

這使照片的名稱在一個字符串,用豎線分隔每個名稱。

0

使用內部查詢獲得計數,然後用照片屬性加入它

select tt.photo,t.photocount from property_photo tt inner join 
(SELECT p.property_id, COUNT(pp.photo) as photocount 
    FROM properties p LEFT JOIN property_photo pp 
ON p.property_id = pp.property_id GROUP BY p.property_id) t on t.property_id=tt.property_id;