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?
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.
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.
The following are the syntax to use the EXISTS operator in MySQL: SELECT col_names. FROM tab_name.
MySQL does not support the EXCEPT operator.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With