使用左连接查询创建列

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?

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

This seems to be a table pivot issue, maybe not work but try it:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(CASE WHEN s.service_data = ''',
      service_data,
      ''' THEN s.service_name ELSE '''' END) AS service_',
      @rowno := @rowno + 1
    )
  ) INTO @sql
FROM (SELECT DISTINCT service_data FROM services) t1
JOIN (SELECT @rowno := 0) t2;
SET @sql = CONCAT('SELECT u.username, ',
                  @sql,
                  ' FROM services s
                    JOIN users u ON s.id_user = u.id
                    GROUP BY u.id');
-- SELECT @sql;
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SQLFiddle Demo

First the all, this problem it is just a sample to explain my real problem. The real problem adds a lot of tables, fields, more joins. The services have (or not) attributes in other table.

The late motive is print a result to export in CSV like this: username | t-shirt | size | food_service | companions
user_1 | yes | XL | yes | 1
user_2 | no | NULL | yes | 2
user_3 | yes | NULL | yes | 2