mysql if 函数 - 子查询作为条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13840181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 15:45:07  来源:igfitidea点击:

mysql if function - subquery as a condition

mysqlsubqueryconditional

提问by shealtiel

I believe the following query is self explanatory:

我相信以下查询是不言自明的:

SELECT IF (SELECT COUNT(*) FROM mytable > 0, 'yes', 'no');

Why doesn't it work? And how should I correct it?

为什么不起作用?我应该如何纠正它?

回答by MichaelRushton

Enclose the subquery in parentheses:

将子查询括在括号中:

SELECT IF ((SELECT COUNT(*) FROM mytable), 'yes', 'no');

回答by Devart

It this what you want?

这是你想要的吗?

SELECT IF(COUNT(*) > 0, 'yes', 'no') FROM mytable;


1:

1:

SELECT
  t1.*,
  (SELECT IF(COUNT(*) > 0, 'yes', 'no') FROM mytable) AS col1
FROM
  table t1;

2:

2:

SELECT
  t1.*,
  t2.*
FROM
  table t1,
  (SELECT IF(COUNT(*) > 0, 'yes', 'no') AS col1 FROM mytable) t2

回答by Luca Rainone

If your query is more complex and this is only a reduced problem, I think this is the better solution for you

如果您的查询更复杂并且这只是一个简化的问题,我认为这对您来说是更好的解决方案

SELECT IF ( (SELECT COUNT(*) AS counter FROM myTable HAVING counter>0) , 'yes', 'no')

so you can do more complex check (i.e. counter > N or multiple conditions)

所以你可以做更复杂的检查(即计数器> N 或多个条件)

回答by Saharsh Shah

Try this:

尝试这个:

SELECT IF((SELECT COUNT(*) FROM mytable) > 0, 'yes', 'no');