蓝海航行家
发布于

如何按父标签获取产品?

有以下表格:

// tags
+----+-----------------------+-----------+
| id |         name          | parent_id |
+----+-----------------------+-----------+
| 1  | Home                  | Null      |
| 2  | Kitchen               | 1         |
| 3  | Serving and reception | 2         |
| 4  | Spoon                 | 3         |
| 5  | Digital               | NULL      |
| 6  | Communication         | 5         |
| 7  | Cellphone             | 6         |
+----+-----------------------+-----------+

// products
+----+------------------------------------------+--------+
| id |                name                      | tag_id | -- this is the deepest tag id
+----+------------------------------------------+--------+
| 1  | Dinner Spoon Set,16 Pcs 7.3" Tablespoons | 4      | 
| 2  | iPhone 14 Promax                         | 7      |
+----+------------------------------------------+--------+

需要为每个 “tag” 实现一个列表页面。所以需要通过以下每个 .s: , , (因为它们都与该产品有关)tags id 5 6 7

知道通过什么查询可以通过标签 #6 (通信) 获得产品 #2 (iPhone 6 Promax) 吗?

注意,可以通过简单的连接获得 tag#7 来获取 product#2:

  SELECT p.*
FROM products p
JOIN tags t 
  ON t.id = p.tag_id
WHERE t.id = 7

但是不知道如何通过更高级别的标签 ID 获取产品。

浏览 (38)
点赞
收藏
1条评论
Klustron小助手
Klustron小助手
在 MySQL 8+ 上,试试使用递归 CTE: WITH RECURSIVE cte (id, name, parent_id, orig_id) AS ( SELECT id, name, parent_id, id AS orig_id FROM tags WHERE parent_id IS NULL UNION ALL SELECT t1.id, t1.name, t1.parent_id, t2.orig_id FROM tags t1 INNER JOIN cte t2 ON t2.id = t1.parent_id ) SELECT MAX(p.name) AS name FROM cte t LEFT JOIN products p ON p.tag_id = t.id GROUP BY t.orig_id HAVING SUM(t.id = 6) > 0;
点赞
评论