我有桌子:
-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)但现在我需要从最近的报告(A 或 B)中获取 LOCATION_ID 和 GPS_ID。
例子:
-Parts-
1
Valve
-ReportA-
1
1
4
9
2
12
2013-02-01
-ReportB-
1
1
113
3
"Changed part"
90
2013-03-27
所以我需要一个可以获取所有部件及其最新位置和 gps id 的 SQL 脚本,上面的结果将产生:
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
但是,我不能按日期 DESC 排序,因为它不是 UNION 返回的字段?
有任何想法吗??