2014-07-20 65 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嗎? –