dtgv52982 2018-07-25 15:19
浏览 65
已采纳

如何正确输出连接表?

I use two tables with an inner join on 'user.ID'='email.ID'.

Every user has a name and an ID. Each email has a username, the email address itself and a corresponding userID. It is possible for a user to have any amount of email addresses.

Usually i print out the results of my queries using:

$row["name"]

I select the data from the DB like this:

SELECT user.name AS name, user.ID as ID, email.user AS user, email.address AS address
FROM user INNER JOIN email ON user.ID=email.ID

I then display a table and output each user in one line.

$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
  <table>
  .
  .
  .
  while($row = mysqli_fetch_assoc($result)) {
    <tr>
      <td>$row["ID"]</td>
      <td>$row["Name"]</td>
      <td>$row["Email"]</td>
    </tr>
  }
}

//this snippet is shortened simplified because I use all HTML in php echoes

When I try to display the email adresses inside the corresponsing users result row I just get the user multiple times with a different email adress in every row.

What I want:

correct_output_table.png

What I get:

wrong_output_table.png

How do I have to select/join/group the tables and columns and how do I output them correctly? Thanks for any help. I´ve been stuck here for days.

EDIT:

output_with_usernames.png

</div>
  • 写回答

1条回答 默认 最新

  • duanaiguang1960 2018-07-25 15:33
    关注
    SELECT 
    u.name,GROUP_CONCAT(e.email SEPARATOR ',') AS email
    FROM users u
    JOIN emails e ON e.user_id=u.id
    

    This should return:

    | User | Email                                           |
    -------|-------------------------------------------------|
    | Nick | email1@mail.com,email2@mail.com,email3@mail.com |
    

    Then in PHP split the email string by comma

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘