SQL从多个表中选择数据

时间:2015-08-27 12:09:12

标签: mysql sql

我尝试使用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组合无济于事。

任何帮助都将不胜感激。

3 个答案:

答案 0 :(得分:0)

您可以使用union allgroup 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;

答案 1 :(得分:0)

试试这个

SELECT tu.URL,COALESCE(table_1.id,0) AS table_1,COALESCE(table_2.id,0) As   
table_2,......,COALESCE(table_n.id,0) AS table_n  FROM Table_URL tu 
LEFT JOIN  table_1 ON tu.URL = table_1.URL
LEFT JOIN  table_2 ON tu.URL = table_2.URL
.
.
LEFT JOIN table_n ON tu.URL = table_n.URL

答案 2 :(得分:0)

您希望SQL语句生成可变数量的列,而不能使用MySQL。

您可以在此处看到一些解决问题的方法:MySQL pivot row into dynamic number of columns

许多报告工具可以让你按照自己的意愿行事,但是使用某种预处理的语句破解MySQL是唯一的方法:

http://buysql.com/mysql/14-how-to-automate-pivot-tables.html

相关问题