MYSQL 连接中的嵌套 Select 语句

发布于 2024-12-01 13:37:12 字数 358 浏览 0 评论 0原文

SELECT * FROM A
JOIN B
ON B.ID = A.ID
AND B.Time =   (SELECT max(Time) 
                            FROM B B2
                            WHERE B2.ID = B.ID)

我正在尝试在 MYSQL 中连接这两个表。不要注意,如果 ID 是唯一的,那么我就不会尝试这样做。我将真正的解决方案浓缩成一幅简化的图画。我试图在最大日期获取并加入表 B 中的某个记录。此过程由 SSIS 包运行,并表示 B2.ID 是未知列。我经常在 MSSQL 中做这样的事情,并且是 MYSQL 的新手。有人有任何指示或想法吗?

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. Don't pay attention to that if the ID is unique then I wouldn't be trying to do this. 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. This procedure is getting run by an SSIS package and is saying B2.ID is an unknown column. I do things like this frequently in MSSQL and am new to MYSQL. Anyone have any pointers or ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深爱成瘾 2024-12-08 13:37:12

我以不同的方式执行这种类型的查询,使用排除联接而不是子查询。您想要查找 B 中对于给定 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

您还可以使用派生表,它的性能应该比使用相关子查询更好。

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:我添加了 greatest-n-per-group 标签。这种类型的 SQL 问题每周都会在 Stack Overflow 上出现,因此您可以按照该标签查看数十个类似的问题及其答案。

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; in other words, where no other row has a greater Time and the same 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)

P.S.: I've added the greatest-n-per-group tag. 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文