我已经采用了相同的数据,但这里只提供了一个
现在我想从最后一行获得text
$sql_query = $connection->query("SELECT DISTINCT `sent_by`, `sent_to` FROM `chat` WHERE `sent_by` = '1' OR `sent_to` = '1'");
if($sql_query->num_rows > 0) {
while ($fetch_data = $sql_query->fetch_array(MYSQLI_ASSOC)) {
if($fetch_data["sent_by"] == 1) {
echo $fetch_data["sent_to"]. " TEXT: ". $fetch_data["text"]. </br>";
} else {
echo $fetch_data["sent_by"]. " TEXT: ". $fetch_data["text"]. </br>";
}
}
}
数据库结构:
抱歉我的英文不好
答案 0 :(得分:0)
更新
如果您有字段id
作为自动增量字段,那么您可以使用此SQL查询获取最后一行:
SELECT DISTINCT `sent_by`, `sent_to`, `id`, `text` FROM `chat` WHERE `sent_by` = '1' OR `sent_to` = '1' ORDER BY `id` DESC LIMIT 1
所以改变这个:
$sql_query = $connection->query("SELECT DISTINCT `sent_by`, `sent_to` FROM `chat` WHERE `sent_by` = '1' OR `sent_to` = '1'");
就此:
$sql_query = $connection->query("SELECT DISTINCT `sent_by`, `sent_to`, `id`, `text` FROM `chat` WHERE `sent_by` = '1' OR `sent_to` = '1' ORDER BY `id` DESC LIMIT 1");
在此新查询中,您可以按降序排列id
字段的值对所有结果进行排序。
如果您要从查询中删除DISTINCT
,则还可以从查询中的SELECT列表中删除id
。
答案 1 :(得分:0)
删除DISTINCT,然后创建查询
$sql_query = $connection->query("SELECT sent_by, sent_to FROM chat WHERE sent_by = '1' OR `sent_to` = '1'");