使用where子句删除行

时间:2014-12-07 16:40:02

标签: php mysql sql sql-delete

我有一个表名论坛, 表格看起来像这样;

id      studentid    description    teacherid   
1        abc123         hi           zxc123
2        abc123        hello         qwe321

我想删除一行, 我试过的是,

<?php 

require_once('Connections/dbcon.php');

mysql_select_db("school", $dbcon);

$student_id=$_GET['student_id'];
$delete=mysql_query("DELETE from forum WHERE student_id='$student_id'")or  die(mysql_error());

echo "<script language='Javascript'>alert('The Forum Successfully Deleted!');

 location.href='tviewforum.php'</script>";   
 ?>

我想在论坛中提供具体信息。如果一个学生创建了两个论坛,我想删除其中一个论坛并保留另一个论坛。

1 个答案:

答案 0 :(得分:0)

当学生创建的论坛超过1个时,您可以保留最大ID

您可以使用group byhaving获取最大ID并删除其他行。

delete T from Table1 T
join ( select max(id) as id , studentid
       from Table1
       where studentid ='abc123'
       group by studentid
       having count(*) >1
      ) NewT
on T.id <> NewT.id
AND T.studentid = NewT.studentid