简体   繁体   English

用PHP更新mysql数据库表

[英]Update mysql database table with PHP

My database has a lot of columns with customers info and some of them are duplicates. 我的数据库中有很多包含客户信息的列,其中有些是重复的。 I need to update "sale" field of the table depending on the IP address (which is known), but only for the the latest entry with such IP address. 我需要根据IP地址(已知)更新表的“ sale”字段,但仅更新具有该IP地址的最新条目。

Here is my table: 这是我的桌子:

|Sale |      IP     | Date     | 
+-----+-------------+----------+
|0    | 109.86.75.1 |2015-12-01|
|0    | 109.86.75.2 |2015-12-05|
|0    | 109.86.75.2 |2015-12-12|
|0    | 109.86.75.4 |2015-12-13|

Let's assume that I need to add changes to customer with ip = 109.86.75.2, I need to change Sale to 1 in the third row, as there are two entries with such IP, but time of the third row is the latest. 假设我需要向ip = 109.86.75.2添加对客户的更改,我需要在第三行中将Sale更改为1,因为有两个具有此类IP的条目,但是第三行的时间是最新的。

Table should look like this after update: 更新后的表应如下所示:

|Sale |      IP     | Date     | 
+-----+-------------+----------+
|0    | 109.86.75.1 |2015-12-01|
|0    | 109.86.75.2 |2015-12-05|
|1    | 109.86.75.2 |2015-12-12|
|0    | 109.86.75.4 |2015-12-13|

I use such PHP code: 我使用这样的PHP代码:

<?php
$servername=...;
$username=...;
$password=...;
$dbname=...;
$ipaddress="109.86.75.2";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql="UPDATE MY_DATABASE_TABLE 
SET Sale='1'
WHERE ip_address = '$ipaddress' AND //Don't know what to add here in where condition... 

if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} 
else {
echo "Error updating record: " . $conn->error;
}

$conn->close();
?>

I tried this after AND, but it doesn't work: 我在AND之后尝试了此操作,但是它不起作用:

date IN (SELECT max(date) FROM MY_DATABASE_TABLE)";

"Error updating record: You can't specify target table 'MY_DATABASE_TABLE' for update in FROM clause" “错误更新记录:您无法在FROM子句中指定目标表'MY_DATABASE_TABLE'进行更新”

Your help is highly appreciated! 非常感谢您的帮助! Thanks in advance! 提前致谢!

You can use an UPDATE with a LEFT JOIN: 您可以将UPDATE与LEFT JOIN一起使用:

UPDATE
  MY_DATABASE_TABLE t1 LEFT JOIN MY_DATABASE_TABLE t2
  ON t1.ip_address=t2.ip_address
     AND t1.date<t2.date
SET
  t1.Sale='1'
WHERE
  t1.ip_address = '109.86.75.2'
  AND t2.date IS NULL

t2.date is NULL when the join does not succeed: the row is the only row with that ip_address, or is the one with the maximum date. 如果连接不成功,则t2.date为NULL:该行是唯一具有该ip_address的行,或者是具有最大日期的行。

Please see a fiddle here . 请看这里的小提琴。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM