MySQL通过一个字段连接多个记录

时间:2017-10-20 09:17:39

标签: mysql join

我坚持这种情况,它是关于连接两个表并返回多个记录。

我们假设我有两个这样的表:

表产品:

+----+-----------+-----------+
| id |    name   | media_id  |
+----+-----------+-----------+
| 1  + product 1 +  32,33,34 +
+----+-----------+-----------+
media_id( VARCHAR(50) )

表媒体:

+----+-----------+------------------------------------------+
| id |    name   |                  path                    +
+----+-----------+------------------------------------------+
| 31 + media 1   +     localhost://uploads/image/image_1    +
+----+-----------+------------------------------------------+
| 32 + media 2   +     localhost://uploads/image/image_2    +
+----+-----------+------------------------------------------+
| 33 + media 3   +     localhost://uploads/image/image_3    +
+----+-----------+------------------------------------------+
| 34 + media 4   +     localhost://uploads/image/image_4    +
+----+-----------+------------------------------------------+

我尝试将JOINWHERE IN子句一起使用:

SELECT 
m.id,
m.name as media_name,
p.name,
p.media_id

FROM 
media as m
JOIN product as p

on m.id in (p.media_id);

和其他JOIN子句但返回结果是:

+----+-----------+-----------+------------+-------------------------+
| id |    name   | image_id  | media_name +          path           + 
+----+-----------+-----------+------------+-------------------------+
| 1  + product 1 +  32,33,34 +  media 2   +   uploads/image/image_1 +
+----+-----------+-----------+------------+-------------------------+

我想要的是返回结果有3条记录:

+----+-----------+-----------+------------+-----------------------+
| id |    name   | image_id  | media_name +          path         +
+----+-----------+-----------+------------+-----------------------+
| 1  + product 1 +     32    +  media 2   + uploads/image/image_2 +
+----+-----------+-----------+------------+-----------------------+
| 2  + product 1 +     33    +  media 3   + uploads/image/image_3 +
+----+-----------+-----------+------------+-----------------------+
| 3  + product 1 +     34    +  media 4   + uploads/image/image_4 +
+----+-----------+-----------+------------+-----------------------+

有谁知道如何加入这样的表?

1 个答案:

答案 0 :(得分:1)

为了实现您正在寻找的内容,您需要对数据库架构稍作更改,从产品表中删除逗号分隔值。

然后,您可以使用链接表,然后可以查询该连接。

<强>产品

| id | name      |
|----|-----------|
| 1  | product 1 |
| 2  | product 2 |
| 3  | product 3 |

product_media链接

| id | product_id | media_id |
|----|------------|----------|
| 1  | 1          | 1        |
| 2  | 1          | 2        |
| 3  | 1          | 3        |

然后,您可以执行检查链接表的查询,并返回您要查找的多行结果。

<强> e.g。

SELECT 
m.id,
m.name as media_name,
p.name as product_name
m.path

FROM 
media as m
LEFT JOIN product_media_links as pl on m.id = pl.media_id
LEFT JOIN products as p on p.id = pl.product_id
如果您愿意,

使用左连接返回没有产品的媒体

另外,如其他人所述,请看一下标准化。它在设计数据库时确实很有帮助,你可以选择它想要的程度。