Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql If Exists Set Value?

Tags:

mysql

I have a query that returns a bunch of information and using a join to join two tables and it works perfectly fine.

But I have a field called tickets which I need to see if there is a time available and if there is even one set it to 1 otherwise set it to 0. So like this.

SELECT 
name,poster,sid,tickets = (IF SELECT id FROM times WHERE shows.tid=times.tid LIMIT 1, 
if value returned set to 1, otherwise set to 0) 
FROM shows JOIN show_info ON (id) WHERE sid=54 order by name ASC

Obviously that is not a correct MySQL statement, but it would give an example of what I am looking for.

Is this possible? Or do I need to do the first select then for a loop through results and do the second select and set value that way? Or is one better performance wise?

like image 638
Steven Avatar asked Apr 15 '12 15:04

Steven


People also ask

How do you check if a record exists in a MySQL database?

To test whether a row exists in a MySQL table or not, use exists condition. The exists condition can be used with subquery. It returns true when row exists in the table, otherwise false is returned. True is represented in the form of 1 and false is represented as 0.

What is if exists in MySQL?

The MySQL EXISTS Operator The EXISTS operator is used to test for the existence of any record in a subquery. The EXISTS operator returns TRUE if the subquery returns one or more records.

What is the correct syntax for exists in MySQL?

The following are the syntax to use the EXISTS operator in MySQL: SELECT col_names. FROM tab_name.

Does except work in MySQL?

MySQL does not support the EXCEPT operator.


2 Answers

I would look at EXISTS it is in most of the cases much faster then to COUNT all the items that matches your where statement. With that said. You query should look something like this:

SELECT 
  name,
  poster,
  sid,
  (
   CASE WHEN EXISTS(SELECT NULL FROM times WHERE shows.tid=times.tid)
      THEN 1 
      ELSE 0
   END 
  )AS tickets 
FROM 
  shows 
  JOIN show_info ON (id) WHERE sid=54 order by name ASC
like image 58
Arion Avatar answered Oct 23 '22 14:10

Arion


Look at CASE statement

SELECT name,poster,sid,
Case WHEN (SELECT count(id) FROM times WHERE shows.tid=times.tid) > 0 THEN 1 else 0 END as Tickets
FROM shows 
JOIN show_info ON (id) 
WHERE sid=54 order by name ASC
like image 29
xQbert Avatar answered Oct 23 '22 16:10

xQbert