![](/img/trans.png)
[英]MySQL query, 3 tables, t1-t2 then update t3. How can I do this the most efficient way?
[英]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);
我想要一份父母所在地及其子女的清單。 如果沒有子代,則打印父代父代:
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?
僅使用一個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結合使用應該效率更高(並且更簡單!)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.