MySQL:使用同一表中输出行中其他行的列数据
一个包含类别和子类别的表格,它们与列 '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' (LIKE '%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 |
+-----+------------+------------+------------+-------------+
我希望这是有道理的。我不想更改表结构或添加关系表,因为它对于简单的类别来说效果非常好且快速。