我有张桌子:
| acctg_cath_id | parent | description |
| 1 | 20 | Bills |
| 9 | 20 | Invoices |
| 20 | | Expenses |
| 88 | 30 |
| 89 | 30 |
| 30 | |我想要创建一个自联接,以便将我的项目分组到父项下。
已经试过了,但没有用:
SELECT
accounting.categories.acctg_cath_id,
accounting.categories.parent
FROM accounting.categories a1, accounting.categories a2
WHERE a1.acctg_cath_id=a2.parent我收到错误:invalid reference to FROM-clause entry for table "categories"
当我尝试:
a.accounting.categories.acctg_cath_id
b.accounting.categories.acctg_cath_id我收到错误:cross-database references are not implemented: a.accounting.categories.acctg_cath_id
期望产出:
我在这里做错什么了?
发布于 2019-06-27 20:42:32
您的语法正在执行交叉连接:FROM accounting.categories a1, accounting.categories a2
尝试以下几点:
SELECT
a2.acctg_cath_id,
a2.parent
FROM accounting.categories a1
JOIN accounting.categories a2 ON (a1.acctg_cath_id = a2.parent)
;检查DBFiddle。
发布于 2019-06-27 20:52:49
你不需要分组,只需要自我加入:
select
c.acctg_cath_id parentid, c.description parent,
cc.acctg_cath_id childid, cc.description child
from (
select distinct parent
from categories
) p inner join categories c
on p.parent = c.acctg_cath_id
inner join categories cc on cc.parent = p.parent
where p.parent = 20如果希望所有父母都带着他们的孩子,可以删除WHERE子句。
见演示。
结果:
> parentid | parent | childid | child
> -------: | :------- | ------: | :-------
> 20 | Expences | 1 | Bills
> 20 | Expences | 9 | Invoices发布于 2019-06-27 22:13:13
你不需要自我连接。你不需要聚合。您只需要一个group by子句:
SELECT ac.*
FROM accounting.categories ac
ORDER BY COALESCE(ac.parent, ac.acctg_cath_id),
(CASE WHEN ac.parent IS NULL THEN 1 ELSE 2 END),
ac.acctg_cath_id;https://stackoverflow.com/questions/56798089
复制相似问题