[英]Nested Select statement in MYSQL join
SELECT * FROM A
JOIN B
ON B.ID = A.ID
AND B.Time = (SELECT max(Time)
FROM B B2
WHERE B2.ID = B.ID)
I am trying to join these two tables in MYSQL. 我试图在MYSQL中加入这两个表。 Don't pay attention to that if the ID is unique then I wouldn't be trying to do this.
不要注意,如果ID是唯一的,那么我不会尝试这样做。 I condensed the real solution to paint a simplified picture.
我浓缩了真实的解决方案来绘制简化的图片。 I am trying to grab and join the table B on the max date for a certain record.
我试图在特定记录的最大日期抓住并加入表B. This procedure is getting run by an SSIS package and is saying B2.ID is an unknown column.
此过程由SSIS包运行,并且说B2.ID是未知列。 I do things like this frequently in MSSQL and am new to MYSQL.
我经常在MSSQL中做这样的事情并且是MYSQL的新手。 Anyone have any pointers or ideas?
任何人有任何指针或想法?
I do this type of query differently, with an exclusion join instead of a subquery. 我以不同的方式执行此类查询,使用排除连接而不是子查询。 You want to find the rows of B which have the max Time for a given ID;
您想要找到具有给定ID的最大时间的B行; in other words, where no other row has a greater Time and the same ID.
换句话说,没有其他行具有更大的时间和相同的ID。
SELECT A.*, B.*
FROM A JOIN B ON B.ID = A.ID
LEFT OUTER JOIN B AS B2 ON B.ID = B2.ID AND B.Time < B2.Time
WHERE B2.ID IS NULL
You can also use a derived table , which should perform better than using a correlated subquery. 您还可以使用派生表 ,该表应该比使用相关子查询更好。
SELECT A.*, B.*
FROM A JOIN B ON B.ID = A.ID
JOIN (SELECT ID, MAX(Time) AS Time FROM B GROUP BY ID) AS B2
ON (B.ID, B.Time) = (B2.ID, B2.Time)
PS: I've added the greatest-n-per-group
tag. PS:我添加了
greatest-n-per-group
标签。 This type of SQL question comes up every week on Stack Overflow, so you can follow that tag to see dozens of similar questions and their answers. 这种类型的SQL问题每周都会出现在Stack Overflow上,因此您可以按照该标记查看数十个类似问题及其答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.