我正在尝试使用 mySQL 从以下格式的多个表 (10+) 中进行选择。
+----------table(n)-----------+
+-----------------------------+
| url | id | ... |
+-----------+-----------+-----+
| url1.com | 12345678 | ... |
| url2.com | 45832458 | ... |
我需要做的是从每个表中检索给定 URL 的 ID,并像这样在一行中返回它。
+--------------table(n)--------------+
+------------------------------------+
| url | table(n) | table(n+1) |
+-----------+-----------+------------+
| url1.com | 12345678 | 8182735 |
但是给定表的 URL 可能不存在,所以我只需要从找到 URL 的表中检索所有 ID。
例如,我有 10 个表,其中 4 个有 URL/id。我需要在一行中检索这 4 个。我已尝试对列使用别名以及各种 JOIN 组合,但均无济于事。
如有任何帮助,我们将不胜感激。
最佳答案
您可以使用union all
和group by
来做到这一点:
select url,
max(id1) as id1, max(id2) as id2, . . .
from ((select url, id as id1, NULL as id2, . . . from table1) union all
(select url, NULL as id1, id as id2, . . . from table1) union all
. . .
) t
group by url;
关于mysql - SQL从多个表中选择数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32248980/