我有两个表,它们是properties
和property_images
。 properties和property_images表中的字段如下所示
属性
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 :(得分: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;
这会将照片的名称放在一个字符串中,每个名称都有一个垂直条。
答案 1 :(得分: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;