【问题标题】:Select query in relational two table mysql在关系两表mysql中选择查询
【发布时间】:2015-11-06 10:57:29
【问题描述】:
+--------------------------------------------+
|             category_table                 |
+----+--------------------+------------------+
+----+--------------------+------------------+
| id | cat_title          | parent           |
+----+--------------------+------------------+
|  1 | cat1               | 0                |
|  2 | cat2               | 1                |
|  3 | cat3               | 1                |
|  4 | cat4               | 2                |
|  5 | cat5               | 2                |
|  6 | cat6               | 2                |
+----+--------------------+------------------+


+---------------------------------------------------------------+
|                       content_table                           |
+----+--------------------+-------------------------------------+
+----+--------------------+------------------+------------------+
| id | title              | category         | content          |
+----+--------------------+------------------+------------------+
|  1 | title1             | 1                | test1            |
|  2 | title2             | 1                | test2            |
|  3 | title3             | 2                | test3            |
|  4 | title4             | 3                | test4            |
|  5 | title5             | 1                | test5            |
|  6 | title6             | 3                | test6            |
|  7 | title7             | 4                | test7            |
|  8 | title8             | 5                | test8            |
|  9 | title9             | 5                | test9            |
| 10 | title10            | 4                | test10           |
| 11 | title11            | 6                | test11           |
+----+--------------------+------------------+------------------+

嗨,

假设父列0表示类别表中的“它是一个主类别”,其他是其他类别的子类别。我想选择所有属于 cat1 和 cat1 子类别的孩子的内容。

【问题讨论】:

  • 您也可以添加预期结果吗?
  • 所有内容表都是此查询的结果,因为所有这些行都是 cat1 的子项
  • 用 MySQL 中的数据库设计没有简单的方法来做到这一点。它需要递归查询/递归调用查询,除非您只想处理固定且数量有限的父/子关系级别。可能您可以在一个过程中隐藏这些多个查询。但是 Google 用于嵌套集模型。
  • 请注意,我会使用NULL 来定义顶级类别。这样您仍然可以在表上设置正确的外键关系。
  • 如果您有机会添加一个新列,您可以在 category_table 中添加一个“顶部”列。当您插入类别数据时,将“顶级类别 ID”指定为顶级类别 ID。通过这种结构,您可以查询您的需求。

标签: mysql sql


【解决方案1】:

检查此查询

select * from content_table where category IN (select id from category_table where parent IN 
(select id from category_table where cat_title = 'cat1'))

【讨论】:

  • 这部分的结果是什么 - select id from category_table where parent IN (select id from category_table where cat_title = 'cat1')
  • 感谢它的工作:) 但不适用于无限的子类别。我该怎么做?
  • 使用“where parent = 0”而不是“where cat_title = 'cat1'”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-21
  • 1970-01-01
相关资源
最近更新 更多