如何缩短这个SQL查询

时间:2017-11-04 16:42:20

标签: mysql sql

我在缩短这个sql代码方面遇到了问题:

SELECT
(SELECT name FROM content_categories ccb WHERE ccb.id = (SELECT parent FROM content_categories cc WHERE cc.id = 57)) AS parent,
(SELECT id FROM content_categories ccb WHERE ccb.id = (SELECT parent FROM content_categories cc WHERE cc.id = 57)) AS parent_id,
(SELECT alias FROM content_categories ccb WHERE ccb.id = (SELECT parent FROM content_categories cc WHERE cc.id = 57)) AS parent_alias,
(SELECT name as subcategory FROM content_categories ccb WHERE ccb.id = 57) as sub,
(SELECT id as subcategory FROM content_categories ccb WHERE ccb.id = 57) as sub_id,
(SELECT alias as subcategory FROM content_categories ccb WHERE ccb.id = 57) as sub_alias

你能帮我解决一些想法。

1 个答案:

答案 0 :(得分:0)

我想你只想要LEFT JOIN

SELECT cp.name as parent, cp.id as parent_id, cp.alias as parent_alias,
       cc.name as sub, cc.id as sub_id, cc.alias as sub_alias
FROM content_categories cc left join
     content_categories cp
     on ccp.id = cc.parent
WHERE cc.id = 57;

唯一的区别是,如果cc.id = 57不存在,则不返回任何行。您的版本将返回一行,其中所有列均为NULL