简体   繁体   English

如果另一个条件满足则更新一个表

[英]Update one table if condition is met in another

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. 我需要的是更新tickets.win下,在给定的playedmatches.ticketidplayedmatches所有行都被处理规则tickets.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. 如果让说,每场比赛有ticketid = 2处理= 1我需要更新tickets.processed 1。此外,如果所有的加工匹配是赢= 1,tickets.win = 1为好。

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. 我有一些想法如何用php中的2个MySQL调用来做到这一点,但我实际上是想弄清楚是否可以只用一个查询来完成。

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); 

You could make a view of playedmatches and aggregate over ticketid with 您可以通过以下方式查看playedmatches并通过ticketid进行汇总

count(ticketid) as a, sum(win) as b, sum(processed) as c

All tickets are processed when a = b. 当a = b时,将处理所有票证。 All processed matches are win when a = b = c. 当a = b = c时,所有已处理的比赛均获胜。

This will give you the information you need to do the two updates via PHP. 这将为您提供通过PHP进行两次更新所需的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM