如何将3个表的结果合并为一个?

时间:2014-08-25 13:07:19

标签: mysql sql

我有3张桌子:A,B和C
他们都有一个共同的专栏名称,“名称” 我需要检查名称7是否在其中任何一个中。

A
name 5
name 6
name 7

B
name 8 
name 9
name 10

C
name 6 
name 7
name 8 
name 9

会产生:

name 7
name 7

因为表A有7而C也有7,所以它总结了它们 SQL会构成什么组合?

6 个答案:

答案 0 :(得分:3)

只需使用 union all 来叠加A,B和C的结果:

select name,
       value
  from A 
 where value = 7

 union all

select name,
       value
  from B 
 where value = 7

 union all

select name,
       value
  from C 
 where value = 7

答案 1 :(得分:2)

您可以使用union合并表格:

select  *
from    (
        select  name
        ,       value
        from    A
        union all
        select  name
        ,       value
        from    B
        union all
        select  name
        ,       value
        from    C
        ) SubQueryAlias
where   value = 8

答案 2 :(得分:0)

Select *
from A,B,C
Where A.name = 7 or B.name = 7 or C.name = 7;

答案 3 :(得分:0)

试试这个:

select name, value from
A inner join B on A.name = B.Name
A inner join C on A.name = C.name 
where A.value = 7 or B.value = 7 or C.value = 7;

答案 4 :(得分:0)

SELECT A.name as NAME_A, B.name as NAME_B, C.name as NAME_C
FROM A
LEFT JOIN B ON B.value = A.value
LEFT JOIN C ON C.value = B.value
WHERE A.value = 7 or B.value = 7 or C.value = 7
UNION
SELECT A.name as NAME_A, B.name as NAME_B, C.name as NAME_C
FROM A
RIGHT JOIN B ON B.value = A.value
RIGHT JOIN C ON C.value = B.value
WHERE A.value = 7 or B.value = 7 or C.value = 7

示例输出

NAME_A | NAME_B | NAME_C
7      | NULL   | 7

答案 5 :(得分:0)

我们也可以尝试 -


SELECT * 
FROM A, B, C
WHERE A.name = B.name OR B.name = C.name OR C.name = A.name