duanba4254 2014-02-14 09:40
浏览 46
已采纳

如何在MySQL和PHP中用户出现一次的用户显示多个结果?

Now I am designing a query to get the user name and what they have posted

here is the fields in table "user" and "post"

user: user_name, u_id

post: p_id, u_id, content

And I want to write a query to display like that

user_name        content

Cherry         hi,i am cherry
               hello
Tom            good day today=)

But not

user_name        content

Cherry         hi,i am cherry
Cherry         hello
Tom            good day today=)

How can I achieve that on PHP in table form?

  • 写回答

4条回答 默认 最新

  • duanmeng3126 2014-02-14 10:07
    关注

    GROUP_CONCAT should be helpful to you. You can read documentation on it here.

    Your query could look like this:

    select user_name, group_concat(content,"
    ") from post group by user_name;
    

    This will group all of the posts together by each user, and then concatenate the content field of all of a user's rows into a single string separated by newline.

    You can see the SQLFiddle with query and results here

    (Keep in mind that SQLFiddle prints its results, by default, in tabular HTML. Choose Run SQL -> Plaintext Output to see the actual newlines printed out)

    EDITED (added content below)

    If you want to use PHP to handle this, you can do the following:

    $query = 'select user_name, group_concat(content,"
    ") as contents from post group by user_name;'
    $result = mysqli_query($query)
    
    print '<table><tr><td>USER NAME</td><td>CONTENTS</td></tr>';
    while ($row = mysqli_fetch_assoc($result)) {
      print '<tr>';
      print '<td>' . $result['user_name'] . '</td>';
      print '<td>' . preg_replace("/
    /", '<br>' . $result['contents']) . '</td>';
      print '</tr>';
    }
    print '</table>';
    

    Here are links to documentation on some of the functions I used in this example:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错