mysql - 如何从两个表中查询相邻的分层数据,其中一行是类别,其余是该类别的内容?

标签 mysql sql database hierarchy

免责声明:我是一名语言学家,而不是计算机科学家。我熟悉编程,但不是专家。该项目涉及濒危语言的大型词典。我需要对大约 1000 个词位进行分类,这样我就可以直观地看到哪些单词丢失了,哪些单词可能会被添加。

<小时/>

我在 MySQL 中有两个表。

  1. 词典表
  2. 类别表

词典表中的每条记录(行)都有一个与类别表(我已重命名为文件夹)的ID相对应的父ID值(pid)。

我根据邻接模型设计了这个(我需要灵活地轻松更改树)。

类别

| folder |     name    | pfolder |
+--------+-------------+---------+
| 1      | Animals     | NULL    |
| 2      | Wild        | 1       |
| 3      | Domestic    | 1       |

词典

| id     | pid   | word        | translation |
+--------+-------+-------------+-------------+
| 1      | 3     | Hund        | dog         |
| 2      | 2     | Rentier     | reindeer    |
| 3      |       | Maus        | Mouse       |
<小时/>

目标

| main    | main_content  |  sub1     | sub1_content | sub2      | sub2_content |
+---------+---------------+-----------+--------------+-----------+--------------+
| Animals | NULL          | Domestic  | Hund         | NULL      | NULL         |
| Animals | NULL          | Wild      | Rentier      | NULL      | NULL         |
| Animals | Maus          | NULL      | NULL         | NULL      | NULL         |

示例查询

我不知道该怎么做,我不能简单地遵循 this tutorial因为我有多个表。

这个简单的查询不应该起作用吗?

SELECT main.name  AS main
FROM categories AS main
    LEFT JOIN hd FROM lexicon ON lexicon.pid = categories.main

最终

我希望最终得到一个有组织的词位的漂亮列表。在这里,我对文件夹使用粗体,对列表项使用斜体。

  • 动物
    • 狂野
      • 食利者
    • 国内
      • 亨德
    • 鼠族

该数据将使用 xelatex 打印。为了简单起见,我将上面的示例表保持在最低限度。词典表的实际查询将包括lexeme正字法词音素词(在国际音标中)。

最佳答案

这有点复杂,但我认为它可以满足您的需求。一项艰难的改变是,如果您想将其显示在“动物”下,则需要将 pid=1 放入 Lexicon 的 Maus 行中。

SELECT
   COALESCE(c3.name, c2.name, c1.name) as main
  ,CASE WHEN (c3.name is null and c2.name is null) then lex.word end as main_content
  ,CASE WHEN (c3.name is null and c2.name is not null) then c1.name 
        WHEN (c3.name is not null and c2.name is not null) then c2.name end as sub1
  ,CASE WHEN (c3.name is null and c2.name is not null) then lex.word end as sub1_content
  ,CASE WHEN (c3.name is not null and c2.name is not null) then c1.name end as sub2
  ,CASE WHEN (c3.name is not null and c2.name is not null) then lex.word end as sub2_content
FROM
  Lexicon lex
LEFT JOIN 
  Categories c1 ON lex.pid = c1.folder
LEFT JOIN
  Categories c2 on c1.pfolder = c2.folder
LEFT JOIN
  Categories c3 on c2.pfolder = c3.folder

SQL Fiddle Demo - 我还添加了一个子类别(WildCats 下的 Wild)来测试 SUB2 是否正确?

关于mysql - 如何从两个表中查询相邻的分层数据,其中一行是类别,其余是该类别的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16145150/

相关文章:

php - 查询数据库时收到错误

java - 选择更新之前是一个好方法还是反之亦然?

javascript - 用于切换 sql 结果的 Jquery 按钮

python - 如何从 Python 中解析 sql 文件?

php - codeigniter 负载模型使用获取参数

mysql - 使用SQL语句将用户添加到mysql中的角色

java - 在mysql查询期间java代码中进行一些迭代后出现无限循环 "hangs"

django - django 中的独特约束

mysql - 使用 Eloquent laravel 检索所有数据

mysql - 计算患者(女性和男性)第一次咨询的次数以及随后的咨询次数