将一列中的结果附加到另一列的结果中

时间:2011-08-24 17:20:20

标签: mysql sql distinct

考虑下表

color   old_color

red     dark red
blue    navy blue
red     light red
green   green

如何从两列中提取不同的值列表,结果如下:

red
blue
green
dark red
navy blue
light red

这基本上是合并以下两个查询的结果:

SELECT DISTINCT color FROM colors;

SELECT DISTINCT old_color FROM colors;

如何将其写入单一陈述?

3 个答案:

答案 0 :(得分:7)

以下是解决方案:

SELECT * FROM
(
    SELECT DISTINCT color FROM colors
    UNION SELECT DISTINCT old_color color FROM colors
) A;

这是一个测试它的脚本:

use test
DROP TABLE IF EXISTS colors;
CREATE TABLE colors (color VARCHAR(20),old_color VARCHAR(20));
INSERT INTO colors VALUES
('red','dark red '),
('blue','navy blue'),
('red','light red'),
('green','green');
SELECT * FROM colors;
SELECT * FROM
(SELECT DISTINCT color FROM colors
UNION SELECT DISTINCT old_color color FROM colors) A;

我在我的电脑上用MySQL 5.5.12试了一下

mysql> use test
DROP TABLE IF EXISTS colors;
CREATE TABLE colors (color VARCHAR(20),old_color VARCHAR(20));
INSERT INTO colors VALUES
Database changed
mysql> DROP TABLE IF EXISTS colors;
SELECT * FROM
(SELECT DISTINCT color FROM colors
UNION SELECT DISTINCT old_color color FROM colors) A;
Query OK, 0 rows affected (0.04 sec)

mysql> CREATE TABLE colors (color VARCHAR(20),old_color VARCHAR(20));
Query OK, 0 rows affected (0.07 sec)

mysql> INSERT INTO colors VALUES
    -> ('red','dark red '),
    -> ('blue','navy blue'),
    -> ('red','light red'),
    -> ('green','green');
Query OK, 4 rows affected (0.06 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM colors;
+-------+-----------+
| color | old_color |
+-------+-----------+
| red   | dark red  |
| blue  | navy blue |
| red   | light red |
| green | green     |
+-------+-----------+
4 rows in set (0.00 sec)

mysql> SELECT * FROM
    -> (SELECT DISTINCT color FROM colors
    -> UNION SELECT DISTINCT old_color color FROM colors) A;
+-----------+
| color     |
+-----------+
| red       |
| blue      |
| green     |
| dark red  |
| navy blue |
| light red |
+-----------+
6 rows in set (0.01 sec)

试一试!!!

答案 1 :(得分:2)

SELECT DISTINCT newtable.*
FROM    
    (SELECT color FROM colors
    UNION 
    SELECT old_color FROM colors) 
AS newtable

更新@RolandoMySQLDBA 2011-08-24 13:46 EDT

您的答案也适用于我的示例数据。这是输出:

mysql> SELECT DISTINCT newtable.*
    -> FROM
    ->     (SELECT color FROM colors
    ->     UNION
    ->     SELECT old_color FROM colors)
    -> AS newtable
    -> ;
+-----------+
| color     |
+-----------+
| red       |
| blue      |
| green     |
| dark red  |
| navy blue |
| light red |
+-----------+
6 rows in set (0.00 sec)

你得到了我的+1,因为你的回答与我的答案基本相同。

答案 2 :(得分:0)

您可以在两个查询中选择两列的颜色,合并结果,并输出不同的颜色:

SELECT DISTINCT tmp.color FROM (
    SELECT color FROM colors
    UNION
    SELECT old_color as color FROM colors
) as tmp