2013-04-03 76 views
0

我有表:學習SQL,抓住最近的配置

-Parts- 
ID 
name 

-ReportA- 
ID 
PART_ID 
LOCATION_ID 
GPS_ID 
USER_ID 
VALVE_ID 
DATE 

-ReportB- 
ID 
PART_ID 
LOCATION_ID 
TYPE_ID 
NOTES 
GPS_ID 
DATE 

(1)我想抓住那有一張報告,A或B的所有部分:

SELECT 
    * 
FROM 
    parts 
WHERE 
    id IN (SELECT id FROM reports_a UNION SELECT id FROM reports_b 

完美(1 )但是現在我需要從最近的報告中獲取LOCATION_ID和GPS_ID(即A或B)。

例子:

-Parts- 
1 
Valve 

-ReportA- 
1 
1 
4 
9 
2 
12 
2013-02-01 

-ReportB- 
1 
1 
113 
3 
"Changed part" 
90 
2013-03-27 

所以我需要一個SQL腳本,可以抓住所有的部件和他們的最新位置和GPS標識,上面的結果會產生:

PART_ID = 1 
LOCATION_ID = 113 
GPS_ID = 90 

所以我改變我的SQL從前面的腳本到:

SELECT 
    id AS PART_ID 
    (
     (
      SELECT location_id FROM reports_a ORDER BY date DESC 
      UNION 
      SELECT location_id FROM reports_b ORDER BY date DESC 
     ) 
     ORDER BY 
      date DESC 
     LIMIT 1 
    ) AS LOCATION_ID 
FROM 
    parts 
WHERE 
    id IN (SELECT id FROM reports_a UNION SELECT id FROM reports_b 

但是,我不能按日期排序因爲它不是字段返回由聯盟?

任何想法??

回答

1

更新:我似乎誤解了質詢時,下面的查詢獲取最新的數據,以供您使用的特定product_id

SELECT 
    id, 
    name, 
    (
     SELECT 
     CONCAT('Location_id: ',location_id, ' gps_id: ', gps_id, ' date: ', `date`) 
     FROM 
     (SELECT `date`,part_id, location_id, gps_id FROM reportA 
     UNION 
     SELECT `date`,part_id, location_id, gps_id FROM reportB 
     ) t 
     WHERE part_id = p.id 
     ORDER BY `date` desc 
     LIMIT 1) 
    as details 
FROM 
    parts p 

SQLFiddle

結構是不正確的,理想情況下,你應該將所有report_data放在單個表格中,其列爲report_type可能是AB

+0

這是怎麼回事en確定JOIN從reportA和reportB獲取最新記錄? – user2233440

+0

@ user2233440我已經更新了答案,您需要將'union'的結果作爲子查詢 – Akash