mysql左连接获取两个查询

时间:2014-08-06 15:16:44

标签: php mysql mysqli mysqli-multi-query

好吧,我有两张桌子,房子和照片。我想说的是 对于每个房子,我想打电话给那个房子的照片数量,以及该照片的最小sort_order号码。

我尝试了不同类型的左连接,一个返回我的总照片很好,但没有返回最小排序顺序,另一个返回我最小排序但不给我全部照片。

我目前的代码是

SELECT properties.p_id,                                         properties.s_property_id,                                   properties.a_property_id,
                            properties.p_advert_heading,                                properties.p_postcode,                                      properties.p_price,
                            properties.p_bedrooms,                                      properties.p_bathrooms,                                     properties.p_status,                                        
                            properties.p_priority,                                      property_photos.photo_url,                              property_photos.sort_order, property_photos.photo_local,                                    
                            COUNT(property_photos.p_id) AS tot_photos                                       
                            FROM properties 
                            LEFT JOIN property_photos on properties.p_id = property_photos.p_id                         
                            WHERE  properties.is_archieved = 0 AND properties.p_status = 1 AND  properties.a_id = 16 
                            GROUP BY properties.p_id 

即:

house_table
----------
property_id
property_name

photo_table
-----------
photo_id
property_id
sort_order

所以我需要找到最多sort_order的照片总数和照片的ID ...

2 个答案:

答案 0 :(得分:0)

您只需使用GROUP BY和聚合函数:

SELECT
    h.property_id,
    h.property_name,
    COUNT(p.photo_id) AS photo_count,
    MIN(p.sort_order) AS min_sort
FROM house_table AS h
LEFT JOIN photo_table AS p
  ON h.property_id = p.property_id
GROUP BY h.property_id

答案 1 :(得分:0)

使用substring_index() / group_concat()方法获取第一个photo_id,您可以最轻松地获取这两个值:

select property_id, count(*) as numphotos,
       substring_index(group_concat(photo_id order by sort_order), ',', 1) as min_photo_id
from photo_table pt
group by property_id;