联合查询后如何更新?

时间:2012-10-25 05:04:34

标签: php mysql database

我有2个表,如下所示,

coin
----
chanceNo
userID
coin_code
date

coin2
----
chanceNo
userID
coin_code
date

我的查询找到'12345'在哪个表格中,如下所示(这是正确且成功的搜索和匹配),

SELECT coin_code from coin WHERE coin_code='12345' UNION 
Select coin_code from coin2 WHERE coin_code='12345';

但是,我坚持在搜索后更新查询。我发现coin_code ='12345'后如何更新。

我知道基本的更新查询是这样的,

UPDATE coin2 SET userID='name', date='12-12-12' WHERE coin_code='12345'

但是,如果“12345”在另一张桌子上,硬币怎么办?我可以知道,如何编写此查询?

2 个答案:

答案 0 :(得分:2)

此查询将告诉您在哪个表中找到了coin_code:

SELECT "coin" which_table, coin_code
FROM coin
WHERE coin_code = '12345'
UNION
SELECT "coin2" which_table, coin_code
FROM coin2
WHERE coin_code = '12345'

现在您拥有了表名,可以将其替换为UPDATE查询:

$row = mysqli_fetch_assoc($sel_stmt);
$upd_stmt = mysqli_prepare("UPDATE {$row[which_table]} SET userID = ?, date = ? WHERE coin_code = ?");

答案 1 :(得分:1)

扩展Barmar的答案你可以做这样的事情,

$sql="SELECT 'coin' which_table, coin_code
      FROM coin
      WHERE coin_code = '12345'
      UNION
      SELECT 'coin2' which_table, coin_code
      FROM coin2
      WHERE coin_code = '12345'";
$result = mysqli_query($sql);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){

     //Now updating the table
     $sql_update = "UPDATE {$row['which_table']} SET userID='name', date='12-12-12' 
               WHERE coin_code='{$row['coin_code']}'";
     mysqli_query($sql_update);
}