mysql> select * from Teams;
+-----------+---------+
| team_name | team_id |
+-----------+---------+
| India | 1 |
| England | 2 |
| Germany | 3 |
| Italy | 4 |
| Spain | 5 |
| Belgium | 6 |
| Brazil | 7 |
| France | 8 |
+-----------+---------+
8 rows in set (0.00 sec)
select * from Players where team_id=7 or team_id=8;
+-----------+----------------+------------+------+--------+--------+---------+
| player_id | player_name | position | age | height | weight | team_id |
+-----------+----------------+------------+------+--------+--------+---------+
| 130 | Jefferson | Goalkeeper | 25 | 6 | 90 | 7 |
| 131 | Dani Alves | Defender | 30 | 6 | 65 | 7 |
| 132 | David Luiz | Defender | 26 | 6 | 73 | 7 |
| 133 | Thiago Silva | Defender | 29 | 6 | 69 | 7 |
| 134 | Marcelo | Defender | 24 | 5 | 65 | 7 |
| 135 | Paulinho | Midfielder | 27 | 6 | 68 | 7 |
| 136 | Ramires | Midfielder | 25 | 6 | 59 | 7 |
| 137 | Oscar | Midfielder | 21 | 5 | 61 | 7 |
| 138 | Lucas Moura | Striker | 19 | 5 | 62 | 7 |
| 139 | Neymar | Striker | 21 | 5 | 63 | 7 |
| 140 | Alex Pato | Striker | 25 | 6 | 69 | 7 |
| 150 | Hugo Lloris | Goalkeeper | 28 | 6 | 75 | 8 |
| 151 | Mathiu Debuchy | Defender | 25 | 6 | 70 | 8 |
| 152 | Philip Mexes | Defender | 34 | 6 | 73 | 8 |
| 153 | Younes Kaboul | Defender | 29 | 6 | 81 | 8 |
| 154 | Patrice Evra | Defender | 34 | 6 | 75 | 8 |
| 155 | Paul Pogba | Midfielder | 21 | 6 | 68 | 8 |
| 156 | Samir Nasri | Midfielder | 27 | 6 | 69 | 8 |
| 157 | Yohan Cabaye | Midfielder | 26 | 6 | 64 | 8 |
| 158 | Frank Ribery | Striker | 28 | 5 | 63 | 8 |
| 159 | Oliver Giroud | Striker | 25 | 6 | 74 | 8 |
| 160 | Karim Benzema | Striker | 24 | 6 | 71 | 8 |
+-----------+----------------+------------+------+--------+--------+---------+
22 rows in set (0.00 sec)
mysql> select * from Matches where match_id=4;
+----------+------------+----------+----------+-----------+-----------+
| match_id | match_date | hometeam | awayteam | homescore | awayscore |
+----------+------------+----------+----------+-----------+-----------+
| 4 | 2014-06-28 | 7 | 8 | 0 | 0 |
+----------+------------+----------+----------+-----------+-----------+
1 row in set (0.00 sec)
(hometeam,awayteam是外键Teams.team_id)
mysql> select * from livescore;
+----------+-----------+----------+---------+
| score_no | player_id | match_id | team_id |
+----------+-----------+----------+---------+
| 1 | 155 | 4 | 8 |
+----------+-----------+----------+---------+
1 row in set (0.00 sec)
(player_id,match_id,team_id are foreign keys of Players,Matches,Teams)
我有一个Players
表格,其中包含所有玩家信息。
我想要的是在'livescore'
中添加新行时homescore,awayscore
应相应增加team_id=8
。即如果玩家属于livescore
中的awayscore
,那么awayteam=8
必须增加+1
{{1}}。
答案 0 :(得分:0)
有一个小技巧可以使用ON DUPLICATE KEY构造在一个查询中完成:
INSERT INTO `table` (`field_a`, `field_b`, `field_c`)
VALUES('val_a', 'val_b', 'val_c')
ON DUPLICATE KEY UPDATE `field_c` = `field_c` + 1;
当使用“ON DUPLICATE KEY”时,复制的键将自动用作WHERE,因此非常舒适。
请记住,您尝试插入的rowa或至少一个键必须是拒绝重复条目的主键或唯一索引,因此此构造将起作用。