gpt4 book ai didi

mysql - 使用 UNION ALL 保存结果

转载 作者:行者123 更新时间:2023-11-30 23:17:29 25 4
gpt4 key购买 nike

我有一个使用 UNION ALL 关键字创建的查询。问题是,当其中一个 SELECT 返回一个空集时,它将被丢弃。我需要它至少返回 NULL 或空行。

我在某处读到,如果每个 SELECT 都有一个唯一索引,它将防止丢弃,但它不起作用。

查询是使用循环创建的,因此日期索引(即“2013-Jun”)会发生变化,仅演示一次选择。

SELECT `products`.`id`, `products`.`ugid`, CONCAT(`products`.`fsg_pre`, `products`.`fsg_suff`) AS `fsg`, `year`, 'Mar' AS `month`, '2012-Mar' AS `index`, `Mar` AS `price`
FROM `prices`
JOIN `products`
ON (`products`.`uuid` = `prices`.`uuid`)
WHERE TRUE
AND `products`.`ugid` = '52777'
AND `products`.`fsg_pre` = 'SU'
AND `products`.`fsg_suff` = '3'
AND `year` = 2012

UNION ALL
[..........]

最佳答案

为什么不按照 IMSoP 的建议使用 LEFT JOIN,例如:

SELECT `products`.`id`, `products`.`ugid`, CONCAT(`products`.`fsg_pre`,
`products`.`fsg_suff`) AS `fsg`, `year`, 'Mar' AS `month`, '2012-Mar' AS `index`,
`Mar` AS `price`
FROM `prices`
LEFT JOIN `products`
ON `products`.`uuid` = `prices`.`uuid`
WHERE `products`.`ugid` = '52777'
AND `products`.`fsg_pre` = 'SU'
AND `products`.`fsg_suff` = '3'
AND `year` = 2012

或 FULL JOIN 总是有一行是否为空。

 SELECT `products`.`id`, `products`.`ugid`, CONCAT(`products`.`fsg_pre`,
`products`.`fsg_suff`) AS `fsg`, `year`, 'Mar' AS `month`, '2012-Mar' AS `index`,
`Mar` AS `price`
FROM `prices`
FULL JOIN `products`
ON `products`.`uuid` = `prices`.`uuid`
WHERE `products`.`ugid` = '52777'
AND `products`.`fsg_pre` = 'SU'
AND `products`.`fsg_suff` = '3'
AND `year` = 2012

参见链接 here直观地查看 JOIN 的工作原理。

关于mysql - 使用 UNION ALL 保存结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16994924/

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