我有两个不同的表: car 和 bike 。我想加入这两个表并使用它们的表名作为字段名称。
car
| id | brand |
--------------------
| 1 | mercedes |
| 2 | bmw |
| 3 | audi |
bike
| id | brand |
--------------------
| 1 | mercedes |
| 2 | bmw |
| 3 | audi |
我想要的选择结果:
| id | vId | brand | type |
-------------------------------
| 1 | 1 | mercedes | bike |
| 2 | 2 | bmw | bike |
| 3 | 3 | harley | bike |
| 4 | 1 | mercedes | car |
| 5 | 2 | bmw | car |
| 6 | 3 | audi | car |
感谢您的帮助。
答案 0 :(得分:0)
您需要使用UNION ALL
SELECT id, brand, 'car' AS type FROM car
UNION ALL
SELECT id, brand, 'bike' AS type FROM bike
答案 1 :(得分:0)
您可以使用 UNION ALL 运算符。 UNION运算符用于组合两个或多个查询的结果集
set @pos=0;
select @pos:=@pos+1 as id ,bikecar.vid, bikecar.brand,bikecar.type
from
(
select id as Vid,brand,'CAR' as type from car
union all
select id as Vid,brand,'Bike' as type from bike
) bikecar