MySQL - 所有表中的SELECT列

时间:2014-03-05 10:09:04

标签: mysql sql select join

如何从所有选定的表中选择一列?喜欢(抛出错误):

SELECT *.id FROM table1, table2, table3, table4

我不会这样做,因为有很多表,他们会改变:

SELECT table1.id, table2.id, table3.id, table4.id FROM table1, table2, table3, table4

只有id,所以这也没用:

SELECT * FROM table1, table2, table3, table4

有一个很好的解决方案吗?

招呼

3 个答案:

答案 0 :(得分:4)

为什么不使用UNION,如下所示:

SELECT id FROM table1
UNION
SELECT id FROM table2
UNION
SELECT id FROM table3
UNION
SELECT id FROM table4

答案 1 :(得分:0)

使用像表这样的别名和前缀名称为列名

的别名

示例:TableName别名

然后使用Table1 t1

中的select t1.columnname
  SELECT t1.id, t2.id, t3.id, t4.id FROM table1 t1, table2 t2, table3 t3, table4 t4

答案 2 :(得分:0)

非常好的解决方案,更不容易出错且更灵活的是按照您希望的顺序写下要获取的所有列:

SELECT 
   t1.id as t1_id, 
   t2.id as t2_id, 
   t3.id as t3_id, 
   t4.id as t4_id 
FROM 
   table1 t1, table2 t2, table3 t3, table4 t4
;

你想做CROSS JOIN吗?

<强>优势: 你有每列的差异名称/参考

相关问题