简体   繁体   English

MySQL SELECT COUNT> 0作为布尔值

[英]MySQL SELECT COUNT > 0 as boolean value

I'm trying to get a true/false value in a column in a select statement which indicates if a count is >0 or not. 我正在尝试在select语句的列中获取true / false值,该值指示计数是否大于0。

I read these docs: http://dev.mysql.com/doc/refman/5.1/en/expressions.html 我阅读了这些文档: http//dev.mysql.com/doc/refman/5.1/en/expressions.html

Which I don't fully understand but they seemed to indicate I could use '>>' in my expression. 我不完全理解,但他们似乎表明我可以在我的表达中使用'>>'。

So I tried this: 所以我尝试了这个:

SELECT COUNT(*)>>0 AS my_bool FROM table GROUP BY id;

It runs and doesnt generate errors or warnings, however the my_bool column just contains the results of the COUNT(*) . 它运行并且不会生成错误或警告,但是my_bool列只包含COUNT(*)的结果。 Is what I'm trying to do possible, if so how? 我正在努力做什么,如果是这样的话怎么样?

PS Yes I know I could just test for x>y in my code that handles the results, I want to know if it is something that can be done in MySQL alone (feel free to explain why it's not advisable, by all means) PS是的我知道我可以在处理结果的代码中测试x> y,我想知道它是否可以在MySQL中完成(随意解释为什么它不可取,无论如何)

In your example you are not using the greater than operator, but a bit shift (>>) . 在您的示例中,您没有使用greater than运算符,而是使用bit shift (>>) If you use 如果你使用

SELECT COUNT(*) > 0 AS my_bool FROM table GROUP BY id;

my_bool will contain 0 or 1 as boolean value. my_bool将包含0或1作为布尔值。

Use the if condition to check and return the true/false. 使用if条件检查并返回true / false。

Example: 例:

SELECT if(COUNT(*)>0,'true','false') AS my_bool FROM table GROUP BY id;

If will check that if the count value is greater than 0 then return true else return false. 如果将检查计数值是否大于0,则返回true,否则返回false。

Try the following: 请尝试以下方法:

SELECT (COUNT(*) <> 0) AS my_bool 
FROM table 
GROUP BY id;

While I think Gene's answer is the better one, you could also use a subquery to do this: 虽然我认为Gene的答案更好,但你也可以使用子查询来做到这一点:

SELECT (
    SELECT COUNT(*) AS my_bool FROM table GROUP BY id
 ) != 0;

If COUNT(*) is zero, the query returns 0, otherwise 1. 如果COUNT(*)为零,则查询返回0,否则返回1。

You could do this - 你可以这样做 -

SET @countValue = (SELECT COUNT(*) FROM table GROUP BY id);  
if @countValue > 0
    return 1;
else
    return 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM