[英]In MySQL how can I write this SQL query in the most efficient way?
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);
I desire a list of parent locations and their children. 我想要一份父母所在地及其子女的清单。 If no child, then print parent parent:
如果没有子代,则打印父代父代:
SQL: 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
Results are correct: 结果正确:
PARENT CHILD LEVEL
California California 1
California Los Angeles 2
California Sacramento 2
California San Francisco 2
My question is did I write the SQL efficiently as possible? 我的问题是我是否有效地编写了SQL?
http://sqlfiddle.com/#!2/87a3d/3 http://sqlfiddle.com/#!2/87a3d/3
How about using just a single JOIN and some inline IFs? 仅使用一个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
This selects all (child) locations and then tries to join parent data where possible. 这将选择所有(子)位置,然后尝试尽可能合并父数据。 Should be a lot more efficient (and simple!) than using UNION with another JOIN.
比将UNION与另一个JOIN结合使用应该效率更高(并且更简单!)。
Demo: http://sqlfiddle.com/#!2/87a3d/21/0 演示: http : //sqlfiddle.com/#!2/87a3d/21/0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.