使用左连接的SQL查询的麻烦

时间:2012-02-23 02:53:39

标签: mysql sql left-join

我在使SQL查询工作时遇到了一些麻烦。

首先是一些背景......我正在处理具有一定数量可用点的事件,供用户注册活动。当用户注册活动时,该特定活动的点数减少一个。如果用户从事件中删除,我将无法将该活动的点数增加一个。

所以我的表格如下。

Activities: this table is used to register users to a specific activity which is defined by table Activity

+----+------------+----------------+----------+
| ID | activityID | activityUserID | eventID  |
+----+------------+----------------+----------+
|  1 |      1     |          2     |       1  |
|  2 |      2     |          2     |       1  |
|  3 |      3     |          2     |       1  |
+----+------------+----------------+---------+

-ID是标识每一行的唯一键。

-activityID用于引用用户注册的活动(表Activity.ID)。例如:用户在事件1中注册活动3:activityID为3,eventID为1

-activityUserID是注册此活动的用户的ID

Activity: this table contains the activities and descriptions. 

+----+---------------------+-------------+---------+
| ID | activityDescription | activityNum | eventID |
+----+---------------------+-------------+---------+
|  1 | test1               |      24     |       1 |
|  2 | test2               |      24     |       1 |
|  3 | test3               |      24     |       1 |
+----+---------------------+-------------+---------+

-ID是标识的唯一值。此值在表活动(activityID)中用于引用用户注册的活动

-activityNum是可用的空缺点数

-eventID特定事件的唯一ID

以下是我遇到问题的查询

 UPDATE activity 
 SET activity.activityNum = activity.activityNum + 1 
 WHERE activity.eventID = ".$eventID."  //$eventID is a obtained based on the page being viewed
 LEFT JOIN activities ON activity.eventID = activities.eventID
 WHERE activity.ID = activities.activityID 

1 个答案:

答案 0 :(得分:3)

我同意Michael,但您的Join语法不正确。做你问的正确方法是:

 UPDATE activity 
 LEFT JOIN activities ON activity.eventID = activities.eventID
 SET activity.activityNum = activity.activityNum + 1 
 WHERE activity.ID = activities.activityID AND activity.eventID = $eventID

虽然这种语法会产生你想要的东西,但我不确定它是不是你想要的。我很困惑表中的eventID在做什么。是否应该将活动“分组”在一起?