Mariadb 简明教程

MariaDB - Delete Query

DELETE 命令从指定表中删除表行,并返回已删除的数量。使用 ROW_COUNT() 函数访问已删除的数量。WHERE 子句指定行,并且在没有它的时候,所有行都将被删除。LIMIT 子句控制已删除的行数。

在针对多行的 DELETE 语句中,它只删除满足条件的行;并且不允许 LIMIT 和 WHERE 子句。DELETE 语句允许从不同数据库中的表中删除行,但不允许从表中删除,然后在子查询中从同一表中选择。

查看以下 DELETE 语法 −

DELETE FROM table_name [WHERE …]

从命令提示符或使用 PHP 脚本执行 DELETE 命令。

The Command Prompt

在命令提示符下,只需使用标准命令 −

root@host# mysql –u root –p password;
Enter password:*******
mysql> use PRODUCTS;
Database changed
mysql> DELETE FROM products_tbl WHERE product_id=133;
mysql> SELECT * from products_tbl WHERE ID_number='133';
ERROR 1032 (HY000): Can't find record in 'products_tbl'

PHP Delete Query Script

在 DELETE 命令语句中使用 mysql_query() 函数 −

<?php
   $dbhost = 'localhost:3036';
   $dbuser = 'root';
   $dbpass = 'rootpassword';
   $conn = mysql_connect($dbhost, $dbuser, $dbpass);

   if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }

   $sql = 'DELETE FROM products_tbl WHERE product_id = 261';
   mysql_select_db('PRODUCTS');
   $retval = mysql_query( $sql, $conn );

   if(! $retval ) {
      die('Could not delete data: ' . mysql_error());
   }

   echo "Deleted data successfully\n";
   mysql_close($conn);
?>

在成功删除数据后,您将看到以下输出 −

mysql> Deleted data successfully
mysql> SELECT * from products_tbl WHERE ID_number='261';
ERROR 1032 (HY000): Can't find record in 'products_tbl'