简体   繁体   English

在mysql查询中连接表?

[英]joining tables in mysql query?

I would like to run a query on two table "products" and "category", There are 30 record in my product table. 我想对两个表“产品”和“类别”运行查询,我的产品表中有30条记录。 product table has a column name category_ids varchar(255),which storing the ids of category in the format like(10,11,12,130,..) for each record of products table. product表有一个列名category_ids varchar(255),它为产品表的每个记录以类型(10,11,12,130,..)的格式存储类别的ID。 In sort a product can be many categories. 在排序中,产品可以是多个类别。 category table having a column name parent_id which is the parent category of that category. 具有列名parent_id的类别表,该列是该类别的父类别。

I want to list the record with all category of that product. 我想列出该产品所有类别的记录。

For example look at one record of the products table having id = 7. 例如,查看id = 7的products表的一条记录。

    product_Id = 7,
    category_ids = '213,215,216',
    product_name = 'Ponds', 
    .....

Means product ponds has three category = category.id = 213, category.id = 215 and category.id = 216. 表示产品池具有三个类别= category.id = 213,category.id = 215和category.id = 216。

I want to list here all three records of ponds like in this format := 我想在这里列出所有三个池塘记录,例如这种格式:=

product_Id | product_name | category_name | parent_category_name
   7           ponds          cream              chemical
   7           ponds          medicine           chemical
   7           ponds          powder             Ayurvedic    

I am trying with this query :- 我正在尝试与此查询:-

select
p.id as product_id,
p.product_name,
child.name as category_name,
parent.name as parent_category_name
from category child 
left join products p on child.id in(p.category_ids) 
left join category parent on parent.id = child.parentid and parent.parentid = 0
where p.id = 7  

The above query getting only one record not all three records as above. 以上查询只获得一条记录,而不是上述所有三条记录。

What condition and joining in this query will be applied to get result as above described. 如上所述,将应用此查询中的条件和加入以获得结果。

Sorry for spending your valuable time. 很抱歉,花费您宝贵的时间。

Any suggestions and ideas would be greatly appreciated. 任何建议和想法将不胜感激。

Thanks a lot. 非常感谢。

Try to change ON condition - 尝试改变ON状态 -

LEFT JOIN products p ON child.id IN(p.category_ids) 

-> - >

LEFT JOIN products p ON FIND_IN_SET(child.id, p.category_ids)

...because: ...因为:

SELECT 1 IN ('1,2,3') find_1, 2 IN ('1,2,3') find_2;
+--------+--------+
| find_1 | find_2 |
+--------+--------+
|      1 |      0 | -- 0 !
+--------+--------+


SELECT FIND_IN_SET(1, '1,2,3') find_1, FIND_IN_SET(2, '1,2,3') find_2;
+--------+--------+
| find_1 | find_2 |
+--------+--------+
|      1 |      2 |
+--------+--------+

GROUP_CONCAT function. GROUP_CONCAT功能。

example: 例:

SELECT p.product_Id, p.product_name, GROUP_CONCAT(c.category) FROM products p
  JOIN category c
    ON FIND_IN_SET(child.id, p.product_Id)
GROUP BY p.product_Id;

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

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