Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql - select true when count is greater than zero

Tags:

mysql

I have the following query.

SELECT COUNT( * ) AS offer_count
  FROM restaurants_offers
WHERE DATE( NOW( ) ) 
   BETWEEN date_start
   AND date_end
AND restaurant_id =1

Now, when count is greater than zero I want to select true else false, instead of count as the query result. How to do that?

like image 988
robert Avatar asked Aug 13 '12 09:08

robert


People also ask

How do you use count in if condition?

A number, expression, cell reference, or text string that determines which cells will be counted. For example, you can use a number like 32, a comparison like ">32", a cell like B4, or a word like "apples". COUNTIF uses only a single criteria. Use COUNTIFS if you want to use multiple criteria.

Can we use SELECT statement in count?

SQL SELECT COUNT(*) functionSQL SELECT statement can be used along with COUNT(*) function to count and display the data values. The COUNT(*) function represents the count of all rows present in the table (including the NULL and NON-NULL values).

Why exists () is faster than Count ()?

Answer: Using the T-SQL EXISTS keyword to perform an existence check is almost always faster than using COUNT(*). EXISTS can stop as soon as the logical test proves true, but COUNT(*) must count every row, even after it knows one row has passed the test.


3 Answers

SELECT COUNT( * ) > 0 AS has_offers
  FROM restaurants_offers
WHERE DATE( NOW( ) ) 
   BETWEEN date_start
   AND date_end
AND restaurant_id =1
like image 86
orasio Avatar answered Oct 25 '22 07:10

orasio


Try this:

SELECT IF(COUNT(*) > 0, 'true', 'false') AS NewResult
  FROM restaurants_offers
 WHERE (DATE(NOW())  BETWEEN date_start AND date_end) AND 
       restaurant_id = 1
like image 21
John Woo Avatar answered Oct 25 '22 05:10

John Woo


SELECT case when COUNT(*) > 0 
            then 1
            else 0
       end AS offer_count
FROM restaurants_offers
WHERE DATE( NOW( ) ) 
BETWEEN date_start
AND date_end
AND restaurant_id =1

or if you need the words trueand false

SELECT case when COUNT(*) > 0 
            then 'true'
            else 'false'
       end AS offer_count
...
like image 44
juergen d Avatar answered Oct 25 '22 06:10

juergen d