12
    $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).")");

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

4

3 回答 3

20
UPDATE a
JOIN   b ON a.id=b.id AND a.p1 = 1 AND b.p1 = 1
SET    a.p2 = 2
于 2012-08-31T07:54:50.590 回答
5

您可以使用INNER JOINwhich perform better thanIN子句来做到这一点:

UPDATE a
       INNER JOIN b
           ON b.id=a.id
              AND b.p1 = 1
              AND a.p1 = 1
SET p2 = 2;
于 2012-08-31T07:55:49.153 回答
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)
于 2012-08-31T07:51:47.340 回答