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
但是,我不能按日期排序因爲它不是字段返回由聯盟?
任何想法??
這是怎麼回事en確定JOIN從reportA和reportB獲取最新記錄? – user2233440
@ user2233440我已經更新了答案,您需要將'union'的結果作爲子查詢 – Akash