使用相同的属性名称分组SELECT请求

时间:2017-05-09 14:53:59

标签: mysql

我尝试合并两个SELECT请求并将其分组到相同的属性中。

我有两个包含很多属性的表,有些是共同的(或者在#34;人类语言和#34中具有相同的含义)。

我已经尝试了CROSS JOINSELECT * FROM table1 (SELECT * FROM TABLE2)),但它无法正常工作。

例如:

表1:

{[Attribute1 = "Name1", 
 Attribute2 = age1, 
 Attribute3 = "Bla", 
 Attribute4 = "Blabla",  
 Attribute5 = 153, 
 Attribute6 = "something"] , 
 [Attribute1=....,....], ...}

表2:

{[Attribute1="Name25", 
 NotInterestingAttribute1="blabla", 
 Attribute15=125, 
 Attribute18="somethingElse"], 
 [Attribute1=....], ...}

我的目标是获得类似

的东西

FinalTable:

{[Attribute1="Name1", Attribute2=125, Attribute3="something"] , 
 [Attribute1="Name25", Attribute2=153, Attribute3="somethingElse"]}

我很抱歉,我试图制作一些真正的桌子,但我失败了。

我不知道我是否足够清楚,如果我没有,请告诉我。

感谢您的帮助!

编辑:

这是我目前正在尝试使用的SELECT请求:

SELECT Attribute1 as Attribute1, 
       Attribute5 as Attribute2, 
       Attribute15 as Attribute2, 
       Attribute6 as Attribute3, 
       Attribute18 as Attribute3 
FROM   Table1, Table2 
WHERE  Attribute1 like '%name%';

1 个答案:

答案 0 :(得分:1)

您正在寻找UNION ALL

SELECT Attribute1 as Attribute1, Attribute5 as Attribute2, Attribute15 as Attribute2, Attribute6 as Attribute3, Attribute18 as Attribute3 
FROM Table1
WHERE Attribute1 like '%name%'
UNION ALL
SELECT Attribute1 as Attribute1, Attribute5 as Attribute2, Attribute15 as Attribute2, Attribute6 as Attribute3, Attribute18 as Attribute3 
FROM Table2
WHERE Attribute1 like '%name%'

但是如果每个表上的字段名称不同,则使用别名,以便它们在同一字段上对齐

SELECT Attribute1 as Attribute1, Attribute5 as Attribute2, Attribute6 as Attribute3
FROM Table1
WHERE Attribute1 like '%name%'
UNION ALL
SELECT Attribute1 as Attribute1, Attribute15 as Attribute2, Attribute18 as Attribute3 
FROM Table2
WHERE Attribute1 like '%name%'