mysql表联合和新列

时间:2016-04-22 05:47:44

标签: mysql union

提供以下两个表格,

电话表:

 PID   NAME
1001 iphone
1002 samsung
1003 sony

pc table:

 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 个答案:

答案 0 :(得分: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 :(得分:1)

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

答案 2 :(得分:0)

使用此查询:

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