简体   繁体   中英

SQL: Join two tables with different type of columns

I have two tables with following columns:

Table 1:

OrderID    RetailerName    SKUs (varchar)    OrderDate
-------------------------------------------------------
123        ABC             1,2               2016-11-11
124        DEF             3,4               2016-11-12

Table 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?

I would suggest normalizing the schema as @Sodmond suggested . 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM