mysql update +(其中+ join)语法

时间:2012-08-31 07:50:39

标签: mysql join where

    $rs = mysql_query("
        SELECT a.id 
        FROM a
        JOIN b ON b.id=a.id
        WHERE 
            b.p1=1 AND 
            a.p1=1");

    while($r = mysql_fetch_assoc($rs))
        $ids[] = $r['id'];

    $rs = mysql_query("
        UPDATE a
        SET p2=2 
        WHERE id IN (".implode(",",$ids).")");

如何在一个查询中执行此操作?

3 个答案:

答案 0 :(得分:20)

UPDATE a
JOIN   b ON a.id=b.id AND a.p1 = 1 AND b.p1 = 1
SET    a.p2 = 2

答案 1 :(得分:5)

您可以使用INNER JOIN执行此操作,其效果优于IN子句:

UPDATE a
       INNER JOIN b
           ON b.id=a.id
              AND b.p1 = 1
              AND a.p1 = 1
SET p2 = 2;

答案 2 :(得分:3)

UPDATE a
SET p2=2 
WHERE id IN (SELECT a.id 
        FROM a
        JOIN b ON b.id=a.id
        WHERE 
            b.p1=1 AND 
            a.p1=1)