【问题标题】:how to select one of each kind from database in php如何从php中的数据库中选择一种
【发布时间】:2016-03-27 11:45:42
【问题描述】:

假设我有一个包含这样数据的数据库

id  userfrom userto body
1   a         b      hello
2   b         a      i am b
3   a         b      everyone
4   b         a      this is great

现在我想选择 a 和 b 中的 1 个,或者你可以说我只想显示 a 和 b 的 1 个帖子,那么 php 中的 mysql 查询应该是什么,我的查询是这样的,告诉我什么我必须接受更改才能获取数据 抱歉写了这么长的代码

<?php
                                $connection10=mysqli_connect('localhost','root','123456789','register');
        $selectquery="select * from messages where userfrom='$msg' or userto='$msg'";
        $resultquery=mysqli_query($connection10,$selectquery);
while($rowstand=mysqli_fetch_array($resultquery))
        {
            $userfrom1=$rowstand['userfrom'];
            $userto1=$rowstand['userto'];
            $body=$rowstand['msgbody'];
                $date=$rowstand['date'];
        $searchquery="select * from register where id='$userto1'";
            $searchresult=mysqli_query($connection10,$searchquery);
            while($bigrow=mysqli_fetch_array($searchresult))
            {
                $profileimage=$bigrow['profilepic'];
            $myfirstname=$bigrow['firstname'];
            $mylastname=$bigrow['lastname'];
            }
        echo '<a href="viewmessages.php?id='.$userto1.'"><img src="'.$profileimage.'" height="50" width="50"></a>'.$myfirstname.' '.$mylastname.'<br>'.$body.'<hr>';}
?>

【问题讨论】:

  • 感谢解决我问题的人
  • 将字符串分配给意外的常量query 不会让您有任何收获。该字符串实际上可能是一个有效的查询,但 PHP 不会神奇地为您执行、获取和处理结果。请学习基础知识。您的问题中只有 1 行 PHP,即使这样也是错误的。 ATM,看起来你在等待有人发布你需要的可复制粘贴代码
  • 老兄,你想要代码而不是我的整个代码
  • 现在请解释一下该代码与您的问题有何关联?你的代码哪里出了问题?
  • 老兄,我只是想举个例子,但显然这里没有人喜欢简单的语言

标签: php mysql


【解决方案1】:

您可以使用GROUP BY 命令,如下所示: http://sqlfiddle.com/#!9/a0057/5/0

【讨论】:

    【解决方案2】:

    select DISTINCT name,id,post from users

    select DISTINCT name,id,post from users GROUP BY name

    【讨论】:

      【解决方案3】:

      您可以使用 GROUP BY 执行此操作,这将在您的示例中返回 2 个结果。使用 GROUP_CONCAT 连接属于同一 name 的帖子可能会很好:

      SELECT name, GROUP_CONCAT(post SEPARATOR ' ') 
      FROM users
      GROUP BY name;
      

      输出:

      一个 |大家好

      b |我是 b 这太棒了

      Fiddle.

      【讨论】:

        猜你喜欢
        • 2012-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-11
        • 1970-01-01
        相关资源
        最近更新 更多