2014-07-20 78 views
0

我使用下面的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),那么执行此操作的最佳方法是什么?

回答

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 ?) 
+0

目前不在家,所以无法测试它。给我一个小时左右:) –

+0

所有看起来不错,谢谢:) –

+0

没问题,很高兴它的工作 –

0

你需要的所有唯一构成地址(地址行和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 
+0

我对同一个地址有两个checkins,一个ID是78,一个ID是79,当我使用你的代码时,它只会选择ID78,它比79更老。你知道为什么? –

+0

ID 78的日期为“2014-07-20 16:00:00”,其中ID 79的日期为“2014-07-20 17:55:25”。它仍然选择较旧的? –

+0

你能帮助Ron吗? –