我有一张桌子:
InvoiceItem
----------------
id
type <- 'ITEM' 'FEE' 'OTHER'
parentid <- InvoiceItem id of the parent invoice item
<some other columns>
如何将此表连接到自身,获取所有InvoiceItem列,其中id =给定id加上一个给出一个true | false 1 | 0如果表中有任何具有给定InvoiceItem id的项目为parentId的。
答案 0 :(得分:2)
使用相关子查询:
SELECT a.*,
EXISTS(SELECT * FROM InvoiceItem b WHERE b.parentid = a.id)
AS has_children
FROM InvoiceItem a
WHERE a.id = ?
使用外部联接:
SELECT a.*, COUNT(b.id) > 0 AS has_children
FROM InvoiceItem a LEFT JOIN InvoiceItem b ON b.parentid = a.id
WHERE a.id = ?