好的,作为SQL新手,我想从数据库A中的一个表中的一个列到数据库B中的表中的另一个列进行映射,然后将这两个映射连接到数据库B中的第三个表中。
实施例: 数据库A,表A,包含一个包含车辆类型的列:
- 2轮摩托车
- 3轮摩托车
- 3轮车
- 4轮车
- 6轮车
- 8轮卡车
- 12轮卡车
- 16轮卡车
- 18轮卡车
数据库B,表B确实有类似的列,但它们更通用:
来自数据库A的
- '2 wheel motorcycle',表A映射到数据库B,表B'摩托车'
来自数据库A的- '3 wheel motorcycle',表A映射到数据库B,表B'摩托车'
- '3 wheel car'=> '汽车'
- '4 wheel car'=> '汽车'
......等等。
在数据库B,表C中,我希望两列都可见,因此可以通过查看行来查看映射到哪些列,例如:
PK | detailed_types | general_types | column x | column y | column z
3 3 wheel car car
4 4 wheel car car
但我该如何解决这个问题呢? 我可以从A和B中选择结果集,但它们之间的映射是我遇到问题的地方。
答案 0 :(得分:0)
我认为这可能会有所帮助,一种模糊连接方法......还有其他方法
select * from detail a
inner join general b on
a.descr like '%' + b.descr + '%'
细节和一般只是我模仿你的表格。这是我的输出
detail general
2 wheel motorcycle, motorcycle
3 wheel motorcycle, motorcycle
3 wheel car, car
4 wheel car, car
6 wheel car, car
8 wheel truck, truck
12 wheel truck, truck
16 wheel truck, truck
18 wheel truck, truck
答案 1 :(得分:0)
INSERT C (detailed_types, general_types)
SELECT detailed_types, general_types FROM A..A
INNER JOIN B ON A.detailed_types like '%'+B.general_types
最好在表上强制使用主键,设置外键并加入FK关系。但你没有指定,所以我的答案基于你的稀疏参数集:)
答案 2 :(得分:0)
或许这样的事情:
SELECT A.detailed_types, B.general_types
FROM A, B
WHERE A.detailed_types LIKE '%' + B.general_types
或者这个:
SELECT A.general_types, B.detailed_types
FROM A
JOIN B ON A.general_types LIKE '%' + B.detailed_types
答案 3 :(得分:0)
好的,所以我没有足够的声誉'添加评论所以这个答案。
我做的是:
--This puts the data from Database A to Database B:
INSERT INTO B (
detailed_types)
SELECT vehicle_types
FROM A
WHERE
(vehicle_type = '2 wheel motorcycle' OR
vehicle_type = '3 wheel motorcycle' OR
vehicle_type = '2 wheel moped' OR
vehicle_type = '3 wheel moped' OR
vehicle_type = '3 wheel car' OR
vehicle_type = '4 wheel car' OR
vehicle_type = '6 wheel car' OR
vehicle_type = '8 wheel bus' OR
vehicle_type = '12 wheel bus' OR
vehicle_type = '8 wheel truck' OR
vehicle_type = '12 wheel truck' OR
vehicle_type = '16 wheel truck' OR
vehicle_type = '18 wheel truck');
-- Update the column and do the mapping like this:
UPDATE B.C SET general_types = 'motorcycle' where detailed_types = '2 wheel motorcycle' OR detailed_types = '3 wheel motorcycle';
UPDATE B.C SET general_types = 'motorcycle' where detailed_types = '2 wheel moped' OR detailed_types = '3 wheel moped';
UPDATE B.C SET general_types = 'car' where detailed_types = '3 wheel car' OR detailed_types = '4 wheel car' OR detailed_types = '6 wheel car';
UPDATE B.C SET general_types = 'truck' where detailed_types = '8 wheel bus' OR detailed_types = '12 wheel bus';
UPDATE B.C SET general_types = 'truck' where detailed_types = '8 wheel truck' OR detailed_types = '12 wheel truck' OR detailed_types = '16 wheel truck' OR detailed_types = '18 wheel truck';
所以可能不是有史以来最有效的SQL,但它确实做到了。谢谢你的答案。