繁体   English   中英

SQL连接两个表并替换和返回列

[英]SQL join on two table and replace and return columns

我正在处理一些带有连接的 SQL 查询,我想从另一个与原始表列值匹配的表中获取相应的值。

例如,我有两个名为ProductCategory的不同表,它们如下所示:

产品:

| 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类型的 Invalid 字符串存储在列名category1category2category3下,我想用表Category中的有效类别名称替换它们。 如果您查看表Category每个类别的 id 与字符串Cloths&Accessories~:/ID1匹配,其中包含ID1

例如: Cloths&Accessories~:/ID1这个字符串中的ID1与表Category的 id=1 相关,即Cloths & Accessories

我必须用有效categories替换并返回表Product的所有category1category2category3列。

什么是最佳的 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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