dongyu6276 2014-08-09 12:35 采纳率: 0%
浏览 18
已采纳

MySql Query / PHP以相同的客户名称获取所有列值

I'm not really sure how to word my problem for the title but here's what i'm trying to do. I have a table:

table1

-----------------------------------
| customer |   phone  | productid |
-----------------------------------
|   John   | 123-4567 |  P123     |
-----------------------------------
|   Bam    | 345-6789 |  P033     |
-----------------------------------
|   John   | 123-4567 |  P432     |
-----------------------------------
|   Gin   | 444-1234 |  P543     |
-----------------------------------
|   Bam    | 345-6789 |  P320     |
-----------------------------------
|   Bam    | 345-6789 |  P675     |
-----------------------------------

And I'm trying to get a result like this:

Customer: John Phone : 123-4567 Products: P123, P432

Customer: Bam Phone: 345-6789 Products: P033, P320, P675

Customer: Gin Phone: 444-1234 Products: P543

I'm not sure if there's a mysql query that would allow me to get this result but I did try to do it on PHP and didn't know where to start. Below is the php code that i'm currently using:

$sql = "SELECT * FROM table1 ORDER BY user";
$result = mysql_query($sql);

while ($row = mysql_fetch_array($result)) {

    echo '</br>Customer: '.$row['customer'].'</br>Phone: '.$row['phone'].'</br>Products: '.$row['productid'].'</br>';
}

I know that i need to add a code inside the while statements that would do "while it's the same user, concatenate productid in to a variable" but I just can't translate it into codes.

Hope this makes sense. Thanks in advance!

  • 写回答

1条回答 默认 最新

  • dongxieyou3314 2014-08-09 12:38
    关注

    You can use GROUP_CONCAT:

    SELECT 
      customer, 
      phone, 
      GROUP_CONCAT(productid SEPARATOR ', ') as product_ids
    FROM table1
    GROUP BY customer
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配