Reputation: 198
I am wondering if this is possible to do in a single query (I'm trying to write one for quite some time now and nothing comes to my mind)
I have two tables:
tickets
+----------+-----+-----------+
| ticketid | win | processed |
+----------+-----+-----------+
| 1 | 0 | 0 |
| 2 | 0 | 0 |
| 3 | 0 | 0 |
+----------+-----+-----------+
playedmatches
+---------+----------+-----+-----------+
| matchid | ticketid | win | processed |
+---------+----------+-----+-----------+
| 1233 | 1 | 1 | 1 |
| 3144 | 1 | 0 | 1 |
| 1334 | 2 | 1 | 1 |
| 4441 | 2 | 1 | 1 |
| 1442 | 3 | 0 | 0 |
| 9723 | 3 | 1 | 1 |
+---------+----------+-----+-----------+
What I need is to update tickets.win and tickets.processed under rule that all rows in playedmatches of the given playedmatches.ticketid are processed. If lets say, every match with ticketid = 2 is processed = 1 I need to update tickets.processed to 1. Further, if all processed matches are win = 1 then tickets.win = 1 as well.
In this case, tickets table should like like:
+----------+-----+-----------+
| ticketid | win | processed |
+----------+-----+-----------+
| 1 | 0 | 1 |
| 2 | 1 | 1 |
| 3 | 0 | 0 |
+----------+-----+-----------+
I have some ideas how to do this with 2 MySQL calls in php but I'm really trying to figure out if it is possible to do with just a single query.
Upvotes: 0
Views: 89
Reputation: 976
You could make a view of playedmatches
and aggregate over ticketid
with
count(ticketid) as a, sum(win) as b, sum(processed) as c
All tickets are processed when a = b. All processed matches are win when a = b = c.
This will give you the information you need to do the two updates via PHP.
Upvotes: 0
Reputation: 370
If you really want to have it in a single query, you can test something like this:
update tickets t join (
select ticketid, if(sum(win) = count(*), 1, 0) as allwin
from playedmatches
group by ticketid
having sum(processed) = count(*)
) j on j.ticketid = t.ticketid
set t.processed = 1,
t.win = if(j.allwin, 1, t.win);
Upvotes: 2