MySQL通过关键字选择最低级别的类别

时间:2018-08-05 00:40:25

标签: mysql

我有一张下表,其中存储了所有以“级别”区分的产品类别数据:

所有类别

record_id   title                     level    parent_category_id   parent_id
-----------------------------------------------------------------------------
7           Cars, Bikes & Boats       0        NULL                 NULL
5687        Car parts & accessories   1        7                    7
5691        Cars                      1        7                    7

parent_id 是指定类别的直接父级

parent_category_id 是指定类别的顶级父级

我有以下查询,当用户输入关键字(例如, “汽车”

SELECT distinct t1.record_id, t1.title, t1.level, t1.keywords 
FROM all_categories t1 
LEFT JOIN all_categories t2
  ON t1.record_id = t2.parent_id
WHERE t1.title LIKE ('%car%') or t1.keywords LIKE ('%car%')

这将返回以下类别数据:

record_id   title                     level 
-------------------------------------------
7           Cars, Bikes & Boats       0        
5687        Car parts & accessories   1      
5691        Cars                      1 

但是,我只想返回最低“级别”的类别。因此,如果将“汽车”作为关键字输入,则我只想返回record_id = 5691或5687,而不是该记录的任何父项(record_id = 7是其父项)。

这显示了一个只有两个级别的简单示例,但是可以有任意多个父级别。

2 个答案:

答案 0 :(得分:1)

您可以通过仅检查与关键字匹配的所有条目都没有子级(假设子级的parent_id引用了父级的record_id)来做到这一点

SELECT  t1.record_id, t1.title, t1.level
FROM all_categories t1 
WHERE (t1.title LIKE '%car%' or t1.keywords LIKE '%car%') AND
   NOT EXISTS (SELECT * 
               FROM all_categories t2 
               WHERE t2.parent_id = t1.record_id)

输出(来自您的样本数据):

record_id   title                       level
5687        "Car parts & accessories"   1
5691        "Cars"                      1

答案 1 :(得分:1)

请尝试

SELECT record_id, title, LEVEL
FROM all_categories 
WHERE (title LIKE '%car%') AND
      LEVEL = (SELECT MIN(t1.level)
FROM all_categories t1 JOIN all_categories t2 ON t1.record_id = t2.record_id
WHERE t1.record_id != t1.parent_category_id AND t1.record_id != t1.parent_id
AND t1.title LIKE '%car%')