SQL- JOIN来自两个表的两列

时间:2012-04-22 23:02:38

标签: mysql sql database union

我需要帮助来制定查询。我想从表A和表B中选择所有DISTINCT颜色。

这是查询所需的结果:

BLACK
RED
YELLOW
BLUE

我有这些表格:

表A

ID   NAME    COLOR
5    SOCKS   BLACK
4    SOCKS   RED

表B

ID   NAME   COLOR 
0    CAR    BLUE
1    BIKE   BLUE
5    TRUCK  YELLOW
10   PLANE  NULL

我试过了:

SELECT DISTINCT A.color FROM A JOIN B ON b.color

但我没有得到所有的颜色。 :(

5 个答案:

答案 0 :(得分:6)

SELECT color FROM A
UNION
SELECT color FROM B
WHERE  color IS NOT NULL -- only filters NULL from B
ORDER  BY color          -- sorts all rows

UNION(而非UNION ALL)删除重复项。无需额外的子查询或DISTINCT

答案 1 :(得分:3)

SELECT 
  A.Color FROM TableA A
WHERE A.Color IS NOT NULL
UNION
SELECT
  B.Color FROM TableB B
    WHERE B.Color IS NOT NULL

我删除了DISTINCT,因为当你将它与UNION结合使用时没有必要 - 我总是倾向于忘记这一点!

答案 2 :(得分:1)

尝试:

SELECT DISTINCT Color
FROM (
    SELECT Color FROM TableA
    UNION ALL
    SELECT Color FROM TableB
) Colors
WHERE NOT Color IS NULL

答案 3 :(得分:1)

http://sqlfiddle.com/#!2/0de4d/5

SELECT distinct
    COLOR
FROM
    (
      select color from TableA
      UNION
      select color from TableB
    ) tmp
WHERE color IS NOT NULL
order by color

已编辑以删除空值

完全披露 - SQL Fiddle是我的网站

答案 4 :(得分:0)

SELECT DISTINCT color FROM 
(
    (
        (SELECT color FROM A WHERE color IS NOT NULL)
        UNION 
        (SELECT color FROM B WHERE color IS NOT NULL)
    ) AS temp
)