简体   繁体   English

PHP-如何从表中选择一个查询

[英]PHP - how to select from a table one query

I got a table that contains ID, Names, message, and time , I want to select from the table only one message query from each ID, Currently I select all the messages, this is my code 我得到了一个包含ID, Names, message, and time的表,我想从该表中仅选择每个ID中的一条消息查询,目前我选择了所有消息,这是我的代码

$query= mysql_query("SELECT * FROM `table` ORDER BY `time`")or die(mysql_error());
while($arr = mysql_fetch_array($query)){
$num = mysql_num_rows($query);
$msg = $arr['message'];
echo '</br>';
echo $msg;
}

That Shows all messages ordered by time, Is there is a way to select only one message query from each ID? 显示按时间排序的所有消息,是否有一种方法可以从每个ID中仅选择一个消息查询?

Thanks, 谢谢,
Klaus 克劳斯

If you want only one message you can use LIMIT like this 如果您只想发送一条消息,则可以像这样使用LIMIT

SELECT * FROM table ORDER BY time LIMIT 1

Or if you want only one message from some id then you can use GROUP BY 或者,如果您只想从某个ID获得一封邮件,则可以使用GROUP BY

SELECT * FROM table ORDER BY time GROUP BY id

Sure, pretty straightforward 当然,很简单

This will fetch all messages given ID: 这将获取给定ID的所有消息:

$id = 10 //Get your id in any way you need
$query= mysql_query("SELECT `message` FROM `table` WHERE `ID` = $id")or die(mysql_error());

while($arr = mysql_fetch_array($query)){
    $num = mysql_num_rows($query);
    $msg = $arr['message'];
    echo $msg;
}

and this will fetch only the first message given ID 这将仅获取给定ID的第一条消息

$id = 10 
$query= mysql_query("SELECT `message` FROM `table` WHERE `ID` = $id LIMIT 1")or die(mysql_error());

$row = mysql_fetch_array($query));
if($row){
    $msg = $row['message'];
    echo $msg;
}else{
    echo 'no messages for id '.$id;
}

暂无
暂无

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

相关问题 如何在类中使用面向对象的 PHP 在一个查询中从一个表中选择和更新 - How to select and update from one table in one query using object oriented PHP inside class php / mysql:从表中选择并在一个查询中更新 - php/mysql: select from table and update in one query 如何使用PHP和mySQli从MySQL数据库中的一个以上的表中选择信息,必须结合单个查询 - How to select information from more then one table in MySQL Database using PHP and mySQli, has to be combined single query 如何从一个查询一个表中选择多个键值? - how to select multiple key value from one table with one query? 如何从一个表而不是两个表中将此MySQL查询更改为SELECT? - How to change this MySQL query to SELECT from one table instead of two? PHP如何在一个select语句中从3个表中查询所需的信息 - PHP How to query information needed from 3 tables in one select statement 如何从三个不同的表php中查询Total的SELECT SUM - How to query SELECT SUM of Total from three different table php 如何使用PHP DOM查询从HTML表中选择文本? - How to select text from HTML table using PHP DOM query? 如何使用 PHP 从一个 MySQL 表列中选择多个值 - How to select multiple values from one MySQL table column with PHP PHP / SQL:仅使用一个查询,如果两个表中都有数据,则从两个表中选择行;否则,仅从一个表中进行SELECT - PHP/SQL: Using only one query, SELECT rows from two tables if data is in both tables, or just SELECT from one table if not
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM