2014-06-16 87 views
1

請原諒我制定合適標題的能力。SQL選擇爲表中的每列返回2行一列

我與列的表:

+-------+----------+------+-----+---------+-------+ 
| Field | Type  | Null | Key | Default | Extra | 
+-------+----------+------+-----+---------+-------+ 
| name | char(20) | YES |  | NULL |  | 
| pri | int(11) | YES |  | NULL |  | 
| sec | int(11) | YES |  | NULL |  | 
+-------+----------+------+-----+---------+-------+ 

與數據,如

+--------+------+------+ 
| name | pri | sec | 
+--------+------+------+ 
| first | 1 | 2 | 
| second | 3 | 4 | 
| third | 5 | 6 | 
+--------+------+------+ 

我想一個選擇,這將使結果:

+--------+------+ 
| name | addr | 
+--------+------+ 
| first | 1 | 
| first | 2 | 
| second | 3 | 
| second | 4 | 
| third | 5 | 
| third | 6 | 
+--------+------+ 

任何幫助不勝感激。

+0

請問你'sec'-'pri' ** **總是等於1? –

回答

0

演示試試這個

SELECT name, pri AS addr 
FROM Table1 
WHERE pri is NOT NULL 

UNION ALL 

SELECT name, sec AS addr 
FROM Table1 
WHERE sec is NOT NULL 

order by 1,2 
+0

我想這是一個很容易的問題。我沒有使用過聯盟,但那是我缺乏的知識。感謝所有的答案。 – BGA

0

像這樣將返回結果集指定:

SELECT p.name 
    , p.pri AS addr 
    FROM mytable p 
UNION ALL 
SELECT s.name 
    , s.sec AS addr 
    FROM mytable s 
ORDER BY 2 ASC 
相關問題