我写了这个mysql查询:
SELECT * , 1 AS haschild
FROM table2
WHERE parentid = '0'
AND pid IN ( SELECT parentid FROM table2 )
UNION
SELECT * , 0
FROM table2
WHERE parentid = '0'
AND pid NOT IN ( SELECT parentid FROM table2 )
ORDER BY pid
但我认为这是如此愚蠢的查询!! 希望你能理解我对这个问题的看法,并指导我写一个更好的查询。
感谢。
答案 0 :(得分:2)
SELECT t1.*,
IF(t2.parentid IS NULL, 0, 1) AS haschild
FROM table2 t1
LEFT JOIN table2 t2 ON t1.pid = t2.parentid
WHERE t1.parentid = 0
ORDER BY t1.pid
注意:
parentid
字段parentid
是一个数字 - 请不要在答案 1 :(得分:0)
尝试:
SELECT * , CASE WHEN pid IN ( SELECT parentid FROM table2 ) THEN 1 ELSE 0 END AS haschild
FROM table2
WHERE parentid = '0'
ORDER BY pid