使用if或case有条件地更新表数据

时间:2013-06-04 13:44:47

标签: mysql sql

我有两张结构相同的桌子。 Table1保留审核数据,table2保留其余数据。

表1

+------+--------+---------------+--------+-----------+
| "id" | "name" | "description" | "type" | "country" |
+------+--------+---------------+--------+-----------+
| "1"  | "a"    | "x"           | "1"    | "US"      |
| "2"  | "b"    | "x"           | "1"    | "UK"      |
+------+--------+---------------+--------+-----------+

表2

+------+-----------+-----------------+--------+-----------+----------+
| "id" |  "name"   |  "description"  | "type" | "country" | "status" |
+------+-----------+-----------------+--------+-----------+----------+
| "1"  | "Title 1" | "Description 1" | "1"    | "US"      | "2"      |
| "2"  | "Title 2" | "Description 2" | "1 "   | "UK"      | "2"      |
+------+-----------+-----------------+--------+-----------+----------+

我运行下面的sql以使用来自table 1的数据更新table 2,并且效果很好。问题是,主持人可以接受更新或拒绝更新。通过将status中的table2设置为0来接受更新。拒绝是通过将其设置为1来完成的。

仅当主持人将table1设置为table2时,才需要从status更新为0。该状态来自像updatestatus.php?status=0&id=1&country=US

这样的PHP脚本

可以执行sql,以便传入status 0然后update both tables elseif status = 1 then update only table2 set status = 1 where id=1 and country =us

UPDATE table1 a
INNER JOIN table2 b
ON a.id = b.id
SET a.name = b.name,
a.description = b.description
WHERE a.id=1;

它的方式是(大致):

$status = 0;//Php

//sql
if ($status = 0) then (run the above update) 
elseif ($status = 1) then (run update for only table2)

我可以使用if与表内的数据一起使用,但是如何做到这样的事情呢?

注意 我不能使用触发器,因为我已经在after update

上使用了一个table2

2 个答案:

答案 0 :(得分:0)

SQL语言中没有办法使用单个Update语句更新两个不同的表。因此,这种类型的逻辑应该在中间层(您的PHP代码)中完成。

答案 1 :(得分:0)

所以我用存储过程来实现这一目标。

CREATE DEFINER=`root`@`localhost` PROCEDURE `p`(IN `status` TINYINT, IN `id` INT, IN `Country` CHAR(2))
    LANGUAGE SQL
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
    COMMENT ''
BEGIN
    IF status = 1 THEN
        UPDATE table2 set status = 1 where id = id and country = country;
    ELSEIF status = 0 THEN
        UPDATE table1 a
        INNER JOIN table2 b
        ON a.id = b.id and a.country = b.country
        SET a.name = b.name,    a.description = b.description
        WHERE a.id=id;
    END IF;
END