我从表格中选择一个列表,如果某个项目有父级,则希望包含父级的标签,如果没有,则只包括-
。
对于此示例,表结构是基本的:
id | label | parent
这是我正在尝试的声明:
SELECT id, label,
IF (parent > 0, (SELECT id FROM meta WHERE parent = m.id), '-') AS parent
FROM meta AS m WHERE type = 'genre'
当项目确实有父项时,我[NULL]
获得parent
。如果我用IF (parent > 0, 'Has parent', '-') AS parent
替换IF语句,则输出正确。
有更好的方法吗?
答案 0 :(得分:2)
你可以左边加入自己。如果父项存在,则父标签将为非空,否则为' - '将被打印。
SELECT
m.id,
m.label,
COALESCE(parent.label, '-') AS parent
FROM
meta AS m LEFT JOIN meta AS parent ON (m.parent = parent.id)
WHERE
m.type = 'genre'
答案 1 :(得分:1)
SELECT id, label,
CASE WHEN COALESCE(parent,0) > 0 THEN
COALESCE(SELECT id FROM meta
WHERE parent = m.id, '-')
ELSE '-' END AS parent
FROM meta AS m WHERE type = 'genre'
COALESCE
将检查NULL
值并将值替换为0