[英]SQL: Join two tables with different type of columns
I have two tables with following columns:我有两个带有以下列的表:
Table 1:表格1:
OrderID RetailerName SKUs (varchar) OrderDate
-------------------------------------------------------
123 ABC 1,2 2016-11-11
124 DEF 3,4 2016-11-12
Table 2:表 2:
SKU(int) Product
--------------------------
1 xx
2 xy
3 xz
4 yx
Expected output:预期输出:
OrderID RetailerName OrderDate Product
--------------------------------------------
123 ABC 2016-11-11 xx
123 ABC 2016-11-11 xy
124 DEF 2016-11-12 xz
124 DEF 2016-11-12 yx
How do I join these two tables based on SKU
ie how do I compare SKUs
(varchar) column from table1 with SKU
(int) column from table2?如何根据
SKU
连接这两个表,即如何比较 table1 中的SKUs
(varchar) 列与 table2 中的SKU
(int) 列?
I would suggest normalizing the schema as @Sodmond suggested .我建议按照@Sodmond 的建议规范化架构。 However, if this is not an option, you could use
find_in_set
for the join condition - it will implicitly convert the int from table2
to a character:但是,如果这不是一个选项,您可以使用
find_in_set
作为连接条件 - 它会将 int 从table2
隐式转换为字符:
SELECT t1.OrderID, RetailerName, OrderDate, Product
FROM table1 t1
JOIN table2 t2 ON FIND_IN_SET(t2.sku, t1.skus) > 0
You need to redesign your schema, Check how I recreate the table for you.您需要重新设计架构,检查我如何为您重新创建表。
table1:
OrderID RetailerName SKUs(int) OrderDate
123 ABC 1 2016-11-11
123 ABC 2 2016-11-11
124 DEF 3 2016-11-12
124 DEF 3 2016-11-12
table2:
SKU(int) Product
1 xx
2 xy
3 xz
4 yx
Avoid storing multiple values in the SKU field, then you will be able to use the join query.避免在 SKU 字段中存储多个值,然后您将能够使用连接查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.