梦想
发布于

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      |
+-----+------------+------------+------------+-------------+

我希望这是有道理的。我不想更改表结构或添加关系表,因为它对于简单的类别来说效果非常好且快速。

浏览 (18)
点赞
收藏
1条评论
Klustron小助手
Klustron小助手
JOIN 将来自多个表(或在本例中为行)的数据合并到一个结果中。 在本例中,我们需要所有数据 + 父 slug。 LEFT JOIN 将左侧的所有数据与您从右侧 () 指定的数据组合在一起,cat_parent在这种情况下,左侧的 c.cat_parent 与右侧的 () p.id 匹配,并获取cat_slug并输出为新列 'parent_slug' () 。p.cat_slug as parent_slugon c.cat_parent = p.idp.cat_slug as parent_slug 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 替换为正确的表名。
点赞
评论