【问题标题】:MySQL how join to empty table?MySQL如何加入空表?
【发布时间】:2018-09-06 18:11:59
【问题描述】:

我有 SQL 查询:

SELECT a.id, b.id
FROM a
LEFT JOIN b ON b.id = 50
WHERE a.something = 'something'

AND a table 真的是空的,应该是这样。但是表 b 不是空的,并且在b.id = 50 上有有效的结果。此查询打印空集。

因此我需要:

| a.id  | b.id  |
|------ |------ |
| null  | 50    | 

【问题讨论】:

  • 你应该使用右连接,阅读stackoverflow.com/questions/5706437/…
  • 如果表 'a' 为空,为什么要使用 a.something='something'?它将提供空结果。除了使用右连接或使用 b 左连接 a
  • 这是对JOIN的滥用。 JOINs(是否LEFT)应该说明(在ON中)这两个表是如何相关的。

标签: mysql join mariadb


【解决方案1】:

反转left 加入或执行right 加入:

SELECT a.id, b.id
FROM b
LEFT JOIN a ON a.something = 'something'
WHERE b.id = 50

SELECT a.id, b.id
FROM a
RIGHT JOIN b ON b.id = 50
WHERE a.something = 'something'

【讨论】:

  • 您的 RIGHT JOIN 将转换为 INNER JOIN。
  • Thx,此解决方案有效,我将非空表交换为 from,并将空表交换为左连接。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-06
  • 2016-09-25
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多