我有一个包含类别和子类别的表,与“cat_parent”列链接在一起,其中包含父类别 ID。
当我搜索某些内容时,我希望结果包含其父级的类别 slug(如果没有父级,则为 NULL)作为虚拟列“parent_slug”。
这是我的桌子:
+-----+------------+------------+------------+
| id | cat_name | cat_slug | cat_parent |
+-----+------------+------------+------------+
| 1 | Cars | cars | 0 |
+-----+------------+------------+------------+
| 2 | Planes | planes | 0 |
+-----+------------+------------+------------+
| 3 | Volvo | volvo | 1 |
+-----+------------+------------+------------+
| 4 | Alfa Romeo | alfa-romeo | 1 |
+-----+------------+------------+------------+
| 5 | Boeing | boeing | 2 |
+-----+------------+------------+------------+
| 6 | Mitsubishi | mitsubishi | 1 |
+-----+------------+------------+------------+
| 7 | Mitsubishi | mitsubishi | 2 |
+-----+------------+------------+------------+
当我搜索“volvo”时,我希望结果是这样的:
+-----+----------+----------+------------+-------------+
| id | cat_name | cat_slug | cat_parent | parent_slug |
+-----+----------+----------+------------+-------------+
| 3 | Volvo | volvo | 1 | cars |
+-----+----------+----------+------------+-------------+
或者搜索 mitsubishi,它会是这样的:
+-----+------------+------------+------------+-------------+
| id | cat_name | cat_slug | cat_parent | parent_slug |
+-----+------------+------------+------------+-------------+
| 6 | Mitsubishi | mitsubishi | 1 | cars |
+-----+------------+------------+------------+-------------+
| 7 | Mitsubishi | mitsubishi | 2 | planes |
+-----+------------+------------+------------+-------------+
并且,想象一下我要搜索“s”(如“%s%”),它看起来像这样:
+-----+------------+------------+------------+-------------+
| id | cat_name | cat_slug | cat_parent | parent_slug |
+-----+------------+------------+------------+-------------+
| 1 | Cars | cars | 0 | NULL |
+-----+------------+------------+------------+-------------+
| 2 | Planes | planes | 0 | NULL |
+-----+------------+------------+------------+-------------+
| 6 | Mitsubishi | mitsubishi | 1 | cars |
+-----+------------+------------+------------+-------------+
| 7 | Mitsubishi | mitsubishi | 2 | planes |
+-----+------------+------------+------------+-------------+
我希望这是有道理的。我不想更改表结构或添加关系表,因为它对于简单类别来说非常好且快速。
而且,是的,三菱确实制造飞机。 :P
提前致谢!
SELECT c.*, p.cat_slug as parent_slug FROM YOUR_TABLE_NAME as c
Left Join YOUR_TABLE_NAME as p on c.cat_parent = p.id;
将 YOUR_TABLE_NAME 替换为正确的表名称。