我有一张桌子车,如下所示
Car_ID | Car_Name
示例数据
Car_ID Car_Name
1 Honda City
2 Ferrari
3 Mercedes
4 Rolls Royce
我在Car表中有数据。现在我还有其他表Car_Detail,如下所示
Car_Detail_ID | Car_ID | Car_Color
现在我要从Car中插入数据到Car_Detail,其中Car_Color将是默认值。如何在单一陈述中实现这一目标?
预期结果
Car_Detail_ID Car_ID Color
1 1 Red
2 2 Red
3 3 Red
4 4 Red
示例数据
购物车
Car_ID Car_Name
1 Honda City
2 Ferrari
3 Mercedes
4 Rolls Royce
颜色表
Color_ID Color_Name
1 Red
2 Yellow
3 Blue
4 Green
预期结果
Car_Detail_ID Car_ID Color_ID
1 1 1
2 2 1
3 3 1
4 4 1
5 1 2
6 2 2
7 3 2
8 4 2
9 1 3
10 2 3
11 3 3
12 4 3
13 1 4
14 2 4
15 3 4
16 4 4
答案 0 :(得分:2)
使用INSERT INTO...SELECT
语句,下面的查询假设Car_Detail_ID
是自动递增的列,而Color
的默认值为Red
INSERT INTO Car_Detail (Car_ID)
SELECT Car_ID
FROM Car
但如果没有,
INSERT INTO Car_Detail (Car_ID, Color)
SELECT Car_ID, 'Red' Color
FROM Car
或类似的东西,
INSERT INTO Car_Detail (Car_Detail_ID, Car_ID, Color)
SELECT Car_ID, Car_ID, 'Red' Color
FROM Car
更新1
使用CROSS JOIN
INSERT INTO CAr_Detail(Car_ID, Color_ID)
SELECT Car_ID, Color_ID
FROM Car CROSS JOIN Color