php - 我已经在php中完成了自我加入,但它给出了错误的结果
问题描述
这是DB
结构
-------------------------------------------------------
| id | cat_title | parent-cat_id | status |
-------------------------------------------------------
| 1 | Main | null | enabled |
| 2 | Child | 1 | enabled |
-------------------------------------------------------
我已经为自加入编写了此查询
SELECT a.id as ID, a.cat_title as Title, s.cat_title as parent_category
FROM store_categories a
LEFT JOIN store_categories s ON s.parent_cat_id =a.id
但它给了我这样的错误结果。因为Main
没有 aparent_category
和Child
有 a parent_category
of Main
。结果,它显示Main
有一个parent_category
和Child
没有。
-----------------------------
| ID | Title | parent-cat_id|
-----------------------------
| 1 | Main | Child |
| 2 | Child | null |
-----------------------------
解决方案
您链接表的两个版本的顺序是错误的,您只需要更改 ON 子句...
SELECT a.id as ID, a.cat_title as Title, s.cat_title as parent_category
FROM store_categories a
LEFT JOIN store_categories s
ON a.parent_cat_id =s.id
推荐阅读
- swift - Swift 泛型:如何表示“无类型”?
- haskell - cabal 的问题:cabal init 不创建 Main.hs
- r - 在 ARM 芯片上运行的 macOS Big Sur 上从源代码编译 R 包
- javascript - 使用 SQL 自动更新 ChartJs
- javascript - 将文本输入到另一个输入字段时清除输入字段
- c++ - 使用 vcpkg 的 C++ restbed 框架
- ruby-on-rails - Rails 6 docker public/assets 403 Forbidden
- c# - 来自原生 iOS 的 Unity AR 视图的屏幕截图
- leaflet - FitBound 方法花费太多时间来设置视图
- go - 检查异常以从 go 调用 C 结构