CREATE TABLE `locationcodes` (
`id` int,
`customer` varchar(100),
`locationcode` varchar(50),
`parentid` int
);
insert into locationcodes values (1, 'Test, Inc.', 'California', NULL);
insert into locationcodes values (2, 'Test, Inc.', 'Los Angeles', 1);
insert into locationcodes values (3, 'Test, Inc.', 'San Francisco', 1);
insert into locationcodes values (4, 'Test, Inc.', 'Sacramento', 1);
我想要一份父母地点及其子女的名单。如果没有孩子,则打印父母:
SQL:
SELECT DISTINCT parent.locationcode as 'Parent', parent.locationcode as 'Child', 1 AS `level`
FROM locationcodes parent
JOIN locationcodes child ON parent.id = child.parentid
WHERE parent.parentid IS NULL
AND parent.customer = 'Test, Inc.'
UNION
SELECT DISTINCT parent.locationcode as 'Parent', child.locationcode as 'Child', 2 AS `level`
FROM locationcodes parent
JOIN locationcodes child ON parent.id = child.parentid
WHERE NOT child.parentid IS NULL
AND child.customer = 'Test, Inc.'
ORDER BY 1, 2
结果是正确的:
PARENT CHILD LEVEL
California California 1
California Los Angeles 2
California Sacramento 2
California San Francisco 2
我的问题是我是否尽可能高效地编写了SQL?
答案 0 :(得分:1)
如何只使用一个JOIN和一些内联IF?
SELECT IFNULL(parent.locationcode,child.locationcode) AS 'Parent', child.locationcode AS 'Child', IF(child.parentid,2,1) AS `level`
FROM locationcodes child
LEFT JOIN locationcodes parent ON parent.id = child.parentid
WHERE child.customer = 'Test, Inc.'
ORDER BY 1, 2
这将选择所有(子)位置,然后尝试尽可能加入父数据。应该比使用UNION和另一个JOIN更高效(而且简单!)。