如何从行和列中选择不同的值

时间:2016-07-04 15:02:02

标签: mysql sql

This is my database table.

这是我的数据库表,包含一些值。从topic1到topic8有不同的主题名称。 我想从所有这些值中访问不同的主题名称。 它的sql查询是什么?

3 个答案:

答案 0 :(得分:1)

使用联合查询:

select topic1 as topic from t union
select topic2 as topic from t union
select topic3 as topic from t union
select topic4 as topic from t union
select topic5 as topic from t union
select topic6 as topic from t union
select topic7 as topic from t union
select topic8 as topic from t;

如果您不想NULL,请添加WHERE条款:

select topic1 as topic from t where topic1 is not null union
select topic2 as topic from t where topic2 is not null union
select topic3 as topic from t where topic3 is not null union
select topic4 as topic from t where topic4 is not null union
select topic5 as topic from t where topic5 is not null union
select topic6 as topic from t where topic6 is not null union
select topic7 as topic from t where topic7 is not null union
select topic8 as topic from t where topic8 is not null;

答案 1 :(得分:0)

试试这个:

SELECT DISTINCT topic1
FROM TABLE
UNION 
SELECT DISTINCT topic2
FROM TABLE
SELECT DISTINCT topic3
FROM TABLE

重复所有必要的列

答案 2 :(得分:0)

澄清答案: 使用UNION运算符的SELECT命令返回自己的不同值。所以它不需要DISTINCT关键字。

使用UNION ALL进行SELECT也会返回重复值。