从联合查询中获取表名?

Pra*_*ase 10 mysql performance union mysqli query-performance

这是我的查询

SELECT Id, productName, Largeimagepath, Discount, Price, Image FROM tablename1 where Active =1 
union 
SELECT Id, productName, Largeimagepath, Discount, Price, Image FROM tablename2 where Active =1
union  
SELECT Id, productName, Largeimagepath, Discount, Price, Image FROM tablename3 where Active =1
Run Code Online (Sandbox Code Playgroud)

它工作正常。

现在我想productName在将来获取各自的表名。

  1. 那么我怎样才能取到它呢?

我试过AS..像这样:

SELECT Id, productName, Largeimagepath, Discount, Price, Image
FROM tablename3 AS tablename
where Active = 1;
Run Code Online (Sandbox Code Playgroud)

但没有得到输出。

  1. 我应该如何更正查询并提高查询性能?

Tar*_*ryn 23

通常,在使用UNION并且您需要知道特定行来自哪个表时,您会使用存储在类似于以下列的硬编码值:

SELECT Id, productName, Largeimagepath, Discount, Price, Image, 'Tablename1' as Source
FROM tablename1 
where Active =1 
union 
SELECT Id, productName, Largeimagepath, Discount, Price, Image, 'Tablename2' as Source
FROM tablename2 
where Active =1
union  
SELECT Id, productName, Largeimagepath, Discount, Price, Image, 'Tablename3' as Source
FROM tablename3 
where Active =1;
Run Code Online (Sandbox Code Playgroud)

这将返回一个Source带有标识符的新列,该列显示该行来自哪个表。

正如@ypercube 在评论中所建议的那样,您可能还想考虑将其更改为 a UNION ALL- 这将包括重复项,但您还将拥有它来自哪个表的标识符。使用 aUNION ALL将消除删除重复项对性能的影响。

SELECT Id, productName, Largeimagepath, Discount, Price, Image, 'Tablename1' as Source
FROM tablename1 
where Active =1 
union all
SELECT Id, productName, Largeimagepath, Discount, Price, Image, 'Tablename2' as Source
FROM tablename2 
where Active =1
union all
SELECT Id, productName, Largeimagepath, Discount, Price, Image, 'Tablename3' as Source
FROM tablename3 
where Active =1;
Run Code Online (Sandbox Code Playgroud)