我正在处理一些SQL查询连接,我想从另一个表中获得与原始表列值匹配的相应值。
例如,我有两个名为Product
和Category
的不同表,它们如下:
产品:
| id | name | category1 | category2 | category3 |
| -- | ------- | ------------------------- |--------------------------- |
| 1 | T-shirt | Cloths&Accessories~:/ID1 | Cloths~:/ID2 | Shirts~:/ID3|
|----|---------|---------------------------|------------- |-------------|
| 2 | T-shirt | Cloths&Accessories~:/ID1 | Cloths~:/ID2 | Shirts~:/ID3|
|----|---------|---------------------------|------------- |-------------|
| 3 | T-shirt | Cloths&Accessories~:/ID1 | Cloths~:/ID2 | Shirts~:/ID3|
|----|---------|---------------------------|------------- |-------------|
| 4 | T-shirt | Cloths&Accessories~:/ID1 | Cloths~:/ID2 | Shirts~:/ID3|
|----|---------|---------------------------|------------- |-------------|
| 5 | T-shirt | Cloths&Accessories~:/ID1 | Cloths~:/ID2 | Shirts~:/ID3|
|----|---------|---------------------------|------------- |-------------|
和类别:
| id | categories |
| -- | -------------------- |
| 1 | Cloths & Accessories |
|----|--------------------- |
| 2 | Cloths |
|----|--------------------- |
| 3 | Shirts |
|----|--------------------- |
问题是,在表Product
中,有Cloths&Accessories~:/ID1
种无效字符串存储在列名称category1
,category2
和category3
下,我想用表Category
中的有效类别名称替换它们。如果您查看表Category
,则每个类别的id与包含ID1
的字符串Cloths&Accessories~:/ID1
匹配。
例如:字符串ID1
中的Cloths&Accessories~:/ID1
与表Category
中的id=1相关,即Cloths & Accessories
我必须用有效的categories
替换并返回表Product
的所有category1
,category2
和category3
列。
最优的SQL连接查询是什么?
您可以使用substring_index
提取ID,然后在其上加入:
SELECT p.id AS id,
p.name AS name,
c1.categories AS category1,
c2.categories AS category2,
c3.categories AS category3
FROM products p
JOIN category c1 ON SUBSTRING_INDEX(p.category1, 'ID', -1) = c1.id
JOIN category c2 ON SUBSTRING_INDEX(p.category2, 'ID', -1) = c2.id
JOIN category c3 ON SUBSTRING_INDEX(p.category3, 'ID', -1) = c3.id