2016-07-04 18 views
0

This is my database table.如何從行和列兩者一起

選擇不同的值,這是一些values.There我的數據庫表有不同的主題名稱從TOPIC1到topic8。 我想從所有這些值訪問不同的主題名稱。 什麼將是它的SQL查詢?

+0

在您採取另一步驟之前,請參閱規範化。數據庫表不是電子表格! – Strawberry

+0

@Strawberry好的,我會感謝你的建議。 –

+0

但是你還沒有:-( – Strawberry

回答

0

要澄清答案: 使用UNION運算符的SELECT命令會自行返回不同的值。所以不需要DISTINCT關鍵字。

SELECT和UNION ALL也會返回重複值。

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; 
+0

未經檢查,你獨有的聲望可能會讓OP覺得這個答案(以及它的數據模型)在RDBMS的上下文中是合適的,但這不是。我不太清楚這只是一個無可挑剔的記錄中的失常。 – Strawberry

+0

它工作。感謝@Gordon Linoff –

0

試試這個:

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

所有重複必要的欄目

相關問題