[英]SQL join on two table and replace and return columns
I am working on some SQL query with joins and I want to get the corresponding value from another table which matches with original table columns values.我正在处理一些带有连接的 SQL 查询,我想从另一个与原始表列值匹配的表中获取相应的值。
For example, I have two different tables named Product
and Category
and they are as follows:例如,我有两个名为Product
和Category
的不同表,它们如下所示:
Products:产品:
| 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|
|----|---------|---------------------------|------------- |-------------|
And Category:和类别:
| id | categories |
| -- | -------------------- |
| 1 | Cloths & Accessories |
|----|--------------------- |
| 2 | Cloths |
|----|--------------------- |
| 3 | Shirts |
|----|--------------------- |
The problem is, in table Product
there is this Cloths&Accessories~:/ID1
kind of Invalid strings stored under column names category1
, category2
and category3
and I want to replace them with valid category names from table Category
.问题是,在表Product
中有这种Cloths&Accessories~:/ID1
类型的 Invalid 字符串存储在列名category1
、 category2
和category3
下,我想用表Category
中的有效类别名称替换它们。 If you look at the table Category
the id of each category matches with string Cloths&Accessories~:/ID1
having ID1
in it.如果您查看表Category
每个类别的 id 与字符串Cloths&Accessories~:/ID1
匹配,其中包含ID1
。
For example: Cloths&Accessories~:/ID1
in this string ID1
is related to id=1 of table Category
which is Cloths & Accessories
例如: Cloths&Accessories~:/ID1
这个字符串中的ID1
与表Category
的 id=1 相关,即Cloths & Accessories
I have to replace and return all of category1
, category2
and category3
columns of table Product
with valid categories
.我必须用有效categories
替换并返回表Product
的所有category1
、 category2
和category3
列。
What would be the optimal SQL join query for this?什么是最佳的 SQL 连接查询?
You could use substring_index
to extract the ID, and then join on it:您可以使用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.