dpps0715 2016-07-19 01:53
浏览 12

使用左连接查询创建列

Well, I have two tables in mysql like this:

TABLE 1 - users
-------------
id | username | user_data
1  | George   | user_data
2  | John     | user_data


TABLE 2 - services
-------------
id | id_user | service_name | service_data
1  | 1       | lunch        | whatever
2  | 1       | dinner       | …
3  | 2       | lunch        | …

Well, with this if I make a query with Left Join like this:

SELECT username, service_name
FROM users
LEFT JOIN services ON users.id = services.id_user
WHERE 1

I got this:

username | service
George   | lunch
George   | dinner
John     | lunch

But I need to print to manage data in excel a grid like this:

username | service_1 | service_2
George   | lunch     | dinner
John     | lunch

I have a lot of rows of users and services and it is not possible make a query asking for services for each user.

Any idea to make this with only one query or any trick in PHP?

  • 写回答

3条回答 默认 最新

  • douxiong2738 2016-07-19 02:05
    关注

    You could use GROUP_CONCAT, but note that this doesn't return the service names in separate columns, but just one column instead. For example:

    SELECT username, GROUP_CONCAT(COALESCE(services.service_name, 'NA')) AS user_services
    FROM users
    LEFT JOIN services
        ON users.id = services.id_user
    GROUP BY users.id;
    

    will return: enter image description here

    I've created this sqlfiddle:

    SQLFiddle

    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100