1

我有一个使用 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
[..........]
4

1 回答 1

0

为什么不按照 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

请参阅此处的链接以直观地了解 JOIN 的工作原理。

于 2013-06-08T02:36:51.307 回答