Mysql 学习SQL,获取最新配置
我有桌子:Mysql 学习SQL,获取最新配置,mysql,sql,Mysql,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
-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)中获取位置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
因此,我需要一个SQL脚本,可以抓取所有零件及其最新位置和gps id,上述结果将产生:
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
但是,我不能按日期说明订购,因为它不是UNION返回的字段
有什么想法吗???更新:我之前似乎误读了这个问题,下面的查询获取了特定
产品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
您使用的结构不正确,理想情况下,您应该将所有报表数据放在一个表中,表的列为report\u type
,可以是a
或B
,这如何确保联接从reportA和reportB获取最新记录?@user2233440我已经更新了答案,您需要将联合的结果包装为子查询