将多行地址分组以仅显示最新行

时间:2014-07-20 16:06:37

标签: mysql sql mysqli

我使用以下SQL从我的数据库表check_in

中获取信息
$properties = $db->prepare("SELECT checkin_id, checkin_client_id, checkin_inventory_id, checkin_property_id, checkin_date, client_username, property_address_line_1, property_town, property_county, property_postcode, property_type, property_rooms, client_first_name, client_last_name, client_organisation_name, client_unique_id, checkin_passcode
            FROM check_in ci
            INNER JOIN properties pr
                ON ci.checkin_property_id = pr.property_id
            INNER JOIN clients cl
                ON ci.checkin_client_id = cl.client_id
            WHERE client_unique_id LIKE ? OR client_first_name LIKE ? OR client_username LIKE ? OR client_organisation_name LIKE ? OR property_address_line_1 LIKE ?")

哪个工作正常,它会带回与搜索词匹配的所有行,但是,结果可能会有相同的地址链接到它们,但是更新的日期(checkin_date)。我只想显示每个地址的最新行(property_address_line_1),最好的方法是什么?

2 个答案:

答案 0 :(得分:1)

见下文,我添加了一个子查询,将结果限制在每个房产的最新办理登机手续。

SELECT checkin_id,
       checkin_client_id,
       checkin_inventory_id,
       checkin_property_id,
       checkin_date,
       client_username,
       property_address_line_1,
       property_town,
       property_county,
       property_postcode,
       property_type,
       property_rooms,
       client_first_name,
       client_last_name,
       client_organisation_name,
       client_unique_id,
       checkin_passcode
  FROM check_in ci
 INNER JOIN properties pr
    ON ci.checkin_property_id = pr.property_id
 INNER JOIN clients cl
    ON ci.checkin_client_id = cl.client_id
 WHERE checkin_date =
       (select max(ci2.checkin_date)
          from check_in ci2
         where ci2.checkin_property_id = ci.checkin_property_id)
   and (client_unique_id LIKE ? OR client_first_name LIKE ? OR
       client_username LIKE ? OR client_organisation_name LIKE ? OR
       property_address_line_1 LIKE ?)

答案 1 :(得分:0)

您需要“分组”所有唯一构成地址的列(address_line_1和property_postcode应该这样做)并显示MAX(checkin_date):

SELECT checkin_id, checkin_client_id, checkin_inventory_id, checkin_property_id, MAX(checkin_date), client_username, property_address_line_1, property_town, property_county, property_postcode, property_type, property_rooms, client_first_name, client_last_name, client_organisation_name, client_unique_id, checkin_passcode
FROM check_in ci
INNER JOIN properties pr
ON ci.checkin_property_id = pr.property_id
INNER JOIN clients cl
ON ci.checkin_client_id = cl.client_id
WHERE client_unique_id LIKE ? OR client_first_name LIKE ? OR client_username LIKE ? OR client_organisation_name LIKE ? OR property_address_line_1 LIKE ?")
GROUP BY address_line_1, property_postcode