[英]Update one table if condition is met in another
我想知道是否可以在单个查询中做到这一点(我现在试图写一个相当长的时间,但我没有想到)
我有两个表:
车票
+----------+-----+-----------+
| ticketid | win | processed |
+----------+-----+-----------+
| 1 | 0 | 0 |
| 2 | 0 | 0 |
| 3 | 0 | 0 |
+----------+-----+-----------+
比赛
+---------+----------+-----+-----------+
| 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 |
+---------+----------+-----+-----------+
我需要的是更新tickets.win下,在给定的playedmatches.ticketid的playedmatches所有行都被处理规则tickets.processed。 如果让说,每场比赛有ticketid = 2被处理= 1我需要更新tickets.processed 1。此外,如果所有的加工匹配是赢= 1,则tickets.win = 1为好。
在这种情况下,票证表应类似于:
+----------+-----+-----------+
| ticketid | win | processed |
+----------+-----+-----------+
| 1 | 0 | 1 |
| 2 | 1 | 1 |
| 3 | 0 | 0 |
+----------+-----+-----------+
我有一些想法如何用php中的2个MySQL调用来做到这一点,但我实际上是想弄清楚是否可以只用一个查询来完成。
如果您真的想在单个查询中使用它,则可以测试以下内容:
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);
您可以通过以下方式查看playedmatches
并通过ticketid
进行汇总
count(ticketid) as a, sum(win) as b, sum(processed) as c
当a = b时,将处理所有票证。 当a = b = c时,所有已处理的比赛均获胜。
这将为您提供通过PHP进行两次更新所需的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.