MySQL是一款廣泛使用的數(shù)據(jù)庫管理系統(tǒng),常用在Web開發(fā)中。在許多業(yè)務(wù)場景中,需要取得上一條記錄的數(shù)據(jù)。下面介紹使用MySQL的語句實現(xiàn)獲取上一條記錄。
SELECT * FROM table WHERE id< current_id ORDER BY id DESC LIMIT 1;
上述語句中,table是數(shù)據(jù)庫中的表名,id是表中的自增字段,current_id是當前行的id值。具體實現(xiàn)方法如下:
/* 連接MySQL數(shù)據(jù)庫 */ $conn = mysqli_connect("localhost","user","password","database"); /* 獲取表中當前行的數(shù)據(jù) */ $result = mysqli_query($conn,"SELECT * FROM table WHERE id = current_id"); $current_row = mysqli_fetch_array($result); /* 獲取上一行的數(shù)據(jù) */ $result = mysqli_query($conn,"SELECT * FROM table WHERE id< current_id ORDER BY id DESC LIMIT 1"); $previous_row = mysqli_fetch_array($result); /* 輸出上一行數(shù)據(jù) */ echo "Previous row: "; echo $previous_row['column1'] . " " . $previous_row['column2'];
使用以上代碼,即可實現(xiàn)獲取當前行的上一行數(shù)據(jù)。