如何从三表获取共同的最大元素

发布于 2025-02-11 16:28:37 字数 365 浏览 1 评论 0原文

我有三张表A,表B和表C 所有三个表都有一个通用的列。

如何从三个表中获取共同的最大值?

这是我的表信息:

表A

id  salary
101  10000
102  15000
103  18000

表B

id salary
110  14000
127  21000
118  15000

表C

id  salary
191  15000
192  20000
193   8000

我所需的输出是:

salary

15000

I have three tables called table a, table b and table c
all the three tables have one common column.

How to get the common maximum value from the three tables?

here is my table info:

table a

id  salary
101  10000
102  15000
103  18000

table b

id salary
110  14000
127  21000
118  15000

table c

id  salary
191  15000
192  20000
193   8000

my required output is :

salary

15000

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

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

发布评论

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

评论(2

且行且努力 2025-02-18 16:28:37

使用联合所有(或union)以使用额外的列来获取所有3个表的薪水然后在中具有集合查询子句检查是否属于所有表格。
最后,使用 限制1 以获取最大common 薪金>薪金

SELECT salary
FROM (
  SELECT 1 id, salary FROM tableA UNION ALL
  SELECT 2 id, salary FROM tableB UNION ALL
  SELECT 3 id, salary FROM tableC 
) t
GROUP BY salary
HAVING COUNT(DISTINCT id) = 3 -- get only the common salaries
ORDER BY salary DESC LIMIT 1;

Use UNION ALL (or UNION) to get the salaries of all 3 tables with an extra column, like an id, which marks the source table and then in the HAVING clause of an aggregation query check if that salary belongs to all tables.
Finally use ORDER BY with LIMIT 1 to get the max common salary:

SELECT salary
FROM (
  SELECT 1 id, salary FROM tableA UNION ALL
  SELECT 2 id, salary FROM tableB UNION ALL
  SELECT 3 id, salary FROM tableC 
) t
GROUP BY salary
HAVING COUNT(DISTINCT id) = 3 -- get only the common salaries
ORDER BY salary DESC LIMIT 1;
暮光沉寂 2025-02-18 16:28:37

您可以在表之间使用内部连接,以确保您仅考虑所有三个表中发生的值。

然后使用max()以获取此类值中的最大值。

SELECT MAX(salary) AS salary
FROM tableA JOIN tableB USING (salary) JOIN tableC USING (salary)

You can use inner joins between the tables to make sure you're only considering values that occur in all three tables.

Then use MAX() to get the greatest of such values.

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