我有桌子:
-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返回的字段?
任何想法??
答案 0 :(得分: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
可能是A
或B