gpt4 book ai didi

MySQL:UNION 加 JOIN

转载 作者:行者123 更新时间:2023-11-29 07:22:46 24 4
gpt4 key购买 nike

我正在尝试弄清楚如何将 UNION 与相同的 JOIN 一起使用,而不是陷入 #2014 - 命令不同步。

我创建了四个简单的表格并为它们编写了简化的代码。主要想法是获得名字中带有“最佳”字样的每把剑、枪和帽子,前提是它们的主人很酷。

SELECT pirate_id, sword, null AS gun, null AS hat, legs = 1 AS is_cool FROM swords as t1
LEFT JOIN
(SELECT legs, pirate_id as pid FROM body_parts) AS t2
ON t1.pirate_id = t2.pid
WHERE sword LIKE '%best%'

UNION
SELECT pirate_id, null AS sword, gun, null AS hat, legs = 1 AS is_cool FROM guns as t3
LEFT JOIN
(SELECT legs, pirate_id as pid FROM body_parts) AS t4
ON t3.pirate_id = t4.pid
WHERE gun LIKE '%best%'

UNION
SELECT pirate_id, null AS sword, null AS gun, hat, legs = 1 AS is_cool FROM hats as t5
LEFT JOIN
(SELECT legs, pirate_id as pid FROM body_parts) AS t6
ON t5.pirate_id = t6.pid
WHERE hat LIKE '%best%'

ORDER BY is_cool DESC, pirate_id ASC

目前,每次我必须使用 UNION 时,我都必须重复 JOIN。我希望有更好的方法...

创建表格:

CREATE TABLE IF NOT EXISTS `body_parts` (
`pirate_id` int(11) NOT NULL,
`legs` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `body_parts` (`pirate_id`, `legs`) VALUES
(1, 0),
(2, 1),
(3, 2);

CREATE TABLE IF NOT EXISTS `guns` (
`pirate_id` int(11) NOT NULL,
`gun` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `guns` (`pirate_id`, `gun`) VALUES
(1, 'best 1');

CREATE TABLE IF NOT EXISTS `hats` (
`pirate_id` int(11) NOT NULL,
`hat` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `hats` (`pirate_id`, `hat`) VALUES
(2, 'best 2');

CREATE TABLE IF NOT EXISTS `swords` (
`pirate_id` int(11) NOT NULL,
`sword` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `swords` (`pirate_id`, `sword`) VALUES
(3, 'best 3');

最佳答案

您可以使用单个左连接来更改使用子查询

    select t1.pirate_id, t1.sword, t1.gun, t1.hat, t2.legs=1  is_cool

from (
SELECT pirate_id, sword, null AS gun, null AS hat
FROM swords
WHERE sword LIKE '%best%'

UNION

SELECT pirate_id, null, gun, null
FROM guns
WHERE gun LIKE '%best%'

UNION
SELECT pirate_id, null, null, hat
FROM hats
WHERE hat LIKE '%best%'
) t1
LEFT JOIN (
SELECT legs, pirate_id
FROM body_parts
) t2 ON t2.pirate_id = t1.pirate_id
ORDER BY is_cool DESC, pirate_id ASC

关于MySQL:UNION 加 JOIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55351351/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com