我有这个SQL:
SELECT MONTH(data) AS MES, cor, CASE month(data)
WHEN 1 THEN 'Janeiro' WHEN 2 THEN 'Fevereiro' WHEN 3 THEN 'Março' WHEN 4 THEN 'Abril' WHEN 5 THEN 'Maio' WHEN 6 THEN 'Junho' WHEN 7 THEN 'Julho' WHEN
8 THEN 'Agosto' WHEN 9 THEN 'Setembro' WHEN 10 THEN 'Outubro' WHEN 11 THEN 'Novembro' WHEN 12 THEN 'Dezembro' END AS MESCOR, COUNT(*)
AS Expr1, CASE cor WHEN 'AM' THEN '2' WHEN 'VD' THEN '1' WHEN 'VM' THEN '3' END AS Expr2
FROM TBINICIATIVAS_PREVISTAS
WHERE (login ='xxxxxxx')
GROUP BY MONTH(data), cor
UNION
SELECT '1', 'VD', 'Janeiro',0,'1'
UNION
SELECT '1', 'AM', 'Janeiro',0,'2'
UNION
SELECT '1', 'VM', 'Janeiro',0,'3'
ORDER BY expr2, mes
但我需要UNION
是有条件的。
类似的东西:
if (select count(*) .... where cond1...) = 0
UNION
SELECT '1', 'VD', 'Janeiro',0,'1'
if (select count(*) ....where cond2...) = 0
UNION
SELECT '1', 'AM', 'Janeiro',0,'2'
if (select count(*) ....where cond3...) = 0
UNION
SELECT '1', 'VM', 'Janeiro',0,'3'
我试过,但我总是遇到语法错误。
有可能吗?
答案 0 :(得分:0)
将您的条件移至WHERE
UNION
SELECT
内的SELECT
条款(UNION
之间除SELECT '1', 'VD', 'Janeiro',0,'0'
UNION
SELECT '1', 'VD', 'Janeiro',0,'1'
WHERE (select count(*) ....where cond1...) = 0
UNION
SELECT '1', 'AM', 'Janeiro',0,'2'
WHERE (select count(*) ....where cond2...) = 0
UNION
SELECT '1', 'VM', 'Janeiro',0,'3'
WHERE (select count(*) ....where cond3...) = 0
之外的其他任何内容
count = 0
此外,我从您的条件中注意到您正在检查该行是否存在,方法是执行NOT EXISTS
。用实际的SELECT '1', 'VD', 'Janeiro',0,'0'
UNION
SELECT '1', 'VD', 'Janeiro',0,'1'
WHERE NOT EXISTS (select 1 ....where cond1...)
UNION
SELECT '1', 'AM', 'Janeiro',0,'2'
WHERE NOT EXISTS (select 1 ....where cond2...)
UNION
SELECT '1', 'VM', 'Janeiro',0,'3'
WHERE NOT EXISTS (select 1 ....where cond3...)
替换它会更快,因为SQL引擎不必实际计算要与0进行比较的所有行,它会在找到行时立即返回。
template <typename T,
std::enable_if_t<std::is_trivially_copyable<T>::value, int> = 0>
inline int test_sfinae(T tc) {
return 1;
}
template <typename T,
std::enable_if_t<!std::is_trivially_copyable<T>::value, int> = 0>
inline int test_sfinae(T ntc) {
return 2;
}