联合表变为1,带有指示相应表条目的标志

时间:2016-10-25 05:08:59

标签: mysql sql

我有两张桌子。

1.home_shop

+---+------------+
|id | product    |   
+---+------------+
| 1 | soap       | 
| 2 | cake       | 
| 3 | biscuit    | 
+---+------------+

2.office_shop

+---+------------+
|id | product    |   
+---+------------+
| 1 | key        | 
| 2 | lock       | 
| 3 | pen        | 
+---+------------+

我想要的是将这两个表合并到一个新表“complete_shop”中,其中一个标志表示“home”和“office” 例如:

+---+------------+-------------+
|id | product    |    flag     |
+---+------------+-------------+
| 1 | soap       | home        |
| 1 | key        | office      |
| 2 | cake       | home        |
| 2 | lock       | office      |
| 3 | biscuit    | home        |
| 3 | pen        | office      |
+---+------------+-------------+

我如何在mysql中做这个联盟请帮帮我。我是初学者

1 个答案:

答案 0 :(得分:4)

执行UNION查询并使用适当的值引入flag列。

SELECT id, product, 'home' AS flag
FROM home_shop
UNION ALL
SELECT id, product, 'office' AS flag
FROM office_shop
ORDER BY id, flag

请注意,您不需要使用子查询在此处订购,您只需指定要使用的列。