我有一个使用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
[..........]
答案 0 :(得分: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
请参阅链接here,直观地了解JOIN的工作原理。