SQL从表中选择并获取表名

时间:2014-04-03 06:05:03

标签: php mysql sql sql-server

我喜欢三个表,它们有一些相同的列,如ID,Name,Image,... 我正在使用此代码从中选择

(SELECT ID, Name FROM `creatures` WHERE ... )
UNION
(SELECT ID, Name FROM `items` ...)
UNION
( ... FROM `anothertable` ... )

我在php中这样做,为每个结果创建一个表的行。现在问题是,我需要知道从哪个表中获取行。我是SQL的新手,我不知道它是否可以以某种方式完成。我虽然喜欢这样的东西:

SELECT ID, Name, TableName FROM ...

有可能吗?

4 个答案:

答案 0 :(得分:3)

您只需在选择中添加一个指示表名称的列;

(SELECT 'creatures' AS tablename, ID, Name FROM `creatures` WHERE ... )
UNION
(SELECT 'items' AS tablename, ID, Name FROM `items` ...)
UNION
( ... FROM `anothertable` ... )

附注,由于您希望所有行,因此使用UNION ALL更快,因为它不需要执行DISTINCT来消除重复项。

答案 1 :(得分:2)

您只需将表名添加为每个查询的字符串文字:

(SELECT 'creatures' AS table_name, ID, Name FROM `creatures` WHERE ... )
UNION
(SELECT 'items' AS table_name, ID, Name FROM `items` ...)
UNION
( ... FROM `anothertable` ... )

修改 请注意,既然您知道来自不同表的两行不能相等,您现在可以使用union all代替union,这可能会给您带来轻微的性能提升。

答案 2 :(得分:1)

试试这个:

(SELECT ID, Name, 'creatures' as TableName FROM `creatures` WHERE ... )
UNION ALL
(SELECT ID, Name, 'items' as TableName FROM `items` ...)
UNION All
( SELECT ID, Name, 'anothertable' as TableName FROM `anothertable` ... )

示例结果:

ID   Name    TableName
1    Name1   creatures
2    Name2   creatures
1    Name3   items
1    Name5   anothertable

答案 3 :(得分:0)

你可以简单地在sql中硬编码,如下所示

(SELECT ID, Name,'creatures' as TableName FROM `creatures` WHERE ... )
UNION
(SELECT ID, Name,'items' as TableName FROM `items` ...)
UNION
( ... FROM `anothertable` ... )