带有子查询的SQL Update语句,在where子句中使用相同的表

时间:2017-03-16 14:32:25

标签: mysql sql phpmyadmin

我目前是学生,我正在努力解决SQL的一个小问题。我想基于同一个表中的过滤结果对表执行更新语句。 Here is the table I have:

这是我到目前为止的查询:

UPDATE ComplexityLessons
SET ACADEMYRATIO = '0,896' 
WHERE (
    SELECT c.START, c.DATE, c.ACTIVITY, c.ACADEMY
from ComplexityLessons c
join (
    SELECT b.ACTIVITY, b.START, b.DATE
    FROM ComplexityLessons b
) as b 
on c.ACTIVITY = b.ACTIVITY and c.DATE = b.DATE and c.START = b.START
having COUNT(DISTINCT ACADEMY) = 2)

总而言之,我想更新专栏" ActivityRatio"只有2个学院同时开展相同活动的地方。当我只使用子查询时,我得到了同时执行相同活动的学院,但我无法弄清楚更新语句。 预先感谢您的帮助 !

1 个答案:

答案 0 :(得分:0)

UPDATE ComplexityLessons SET ACADEMYRATIO = '0,896' 
WHERE ( SELECT c.START, c.DATE, c.ACTIVITY, c.ACADEMY 
        from ComplexityLessons c 
join ( SELECT b.ACTIVITY, b.START, b.DATE 
       FROM ComplexityLessons b ) as b 
on c.ACTIVITY = b.ACTIVITY and c.DATE = b.DATE and c.START = b.START 
having COUNT(DISTINCT ACADEMY) = 2)

应该具有条件的位置和子查询应该返回id。 例如

UPDATE ComplexityLessons SET ACADEMYRATIO = '0,896'
WHERE <id> in ( SELECT <id> from ComplexityLessons c 
join ( SELECT b.ACTIVITY, b.START, b.DATE 
       FROM ComplexityLessons b ) as b 
on c.ACTIVITY = b.ACTIVITY and c.DATE = b.DATE and c.START = b.START 
having COUNT(DISTINCT ACADEMY) = 2)

应该是表之间的foriegn键。