2016-04-22 129 views
1

舉兩個在下表中,MySQL表聯盟和新列

電話表:

PID NAME 
1001 iphone 
1002 samsung 
1003 sony 

PC表:

CID NAME 
1001 HP 
1002 XPS 

我怎樣才能得到結果表?

DID TYPE NAME 
1001 PHONE iphone 
1002 PHONE samsung 
1003 PHONE sony 
1001 PC HP 
1002 PC XPS 

我認爲這應該使用UNION,但如何處理TYPE?

回答

3

如果你想重複結果,你應該使用UNION ALL,否則你可以使用UNION消除重複的值。

您的查詢會是這樣,

select pid as DID,'PHONE' as TYPE,name from phone 
UNION all 
select CID as DID,'PC' as TYPE,name from PC; 

這兩個表中選擇所有記錄。

1
SELECT PID AS DID, 'PHONE' AS TYPE, NAME FROM Phone 
UNION ALL 
SELECT CID AS DID, 'PC' AS TYPE, NAME FROM PC; 
+1

聯盟將消除重複記錄。 例如。 1001,1002只會被挑選一次。 聯盟所有將做的伎倆。 – Priyanshu

0

使用此查詢:

select pid as DID,'PHONE' as TYPE, name from phone 
UNION 
select cid as DID,'PC' as TYPE, name from PC;