我有以下查询:
SELECT ty.id, ty.type, ty.pid, if(ty.pid = 0, '-',
(select ty.type from bid_type ty where ty.pid != 0 and ty.id = ty.pid)) as parent,
ty.code, ty.description, ty.icon,
date_format(ty.adate, '%m-%d-%Y %H:%i:%s') as adate,
date_format(ty.edate, '%m-%d-%Y %H:%i:%s') as edate, ty.status
FROM (bid_type ty)
我希望通过此查询获得孩子的“父母”。但它为“父母”返回空结果。有人可以指导我做错了什么以及如何纠正。
提前致谢
答案 0 :(得分:1)
尝试为两个表提供不同的别名。在您的代码中,bid_type
的别名为ty
两次。
答案 1 :(得分:0)
您需要正确对表进行别名以获取所需的数据。此外,您应该使用JOIN,而不是使用子查询来选择父类型。可能是外部联接,因为您的查询暗示此表中的父子关系是可选的。
这应该适合你:
SELECT ty.id, ty.type, ty.pid,
if(ty.pid = 0, '-', p.type) as parent,
ty.code, ty.description, ty.icon,
date_format(ty.adate, '%m-%d-%Y %H:%i:%s') as adate,
date_format(ty.edate, '%m-%d-%Y %H:%i:%s') as edate, ty.status
FROM bid_type ty
LEFT OUTER JOIN bid_type p on p.id = ty.pid