我有两张桌子: 用户 user_licenses。 他们的结构如下:
+------------+-----------+----------+
| users table |
+------------+-----------+----------+
| identifier | firstname | lastname |
+------------+-----------+----------+
| 122 | John | Doe |
| 123 | Johnny | Dough |
| 124 | Martin | Pie |
+------------+-----------+----------+
+------------+-----------+------------+
| user_licenses table |
+----+-------------+-------+----------+
| id | type | owner | warnings |
+----+-------------+-------+----------+
| 1 | drive | 122 | 2 |
| 2 | drive_bike | 122 | 2 |
| 3 | drive_truck | 123 | 3 |
| 4 | drive_bike | 124 | 2 |
| 5 | drive | 123 | 2 |
| 6 | drive_truck | 124 | 3 |
+----+-------------+-------+----------+
问题是,我想创建一个输出以下内容的结果:
identifier, firstname, lastname, typesOfLicenses(Commaseperated?), HowManyWarningsForEachLicense(Commaseperated?)
我不知道如何去做: 我试过在这样的查询中加入这两个:
SELECT users.identifier, users.firstname, users.lastname, user_licenses.type, user_licenses.warnings FROM users INNER JOIN user_licenses ON users.identifier=user_licenses.owner;
但这会为每个人及其许可证创建多个结果。 我想每人一个结果,然后他们的许可证合并到类型行(可能是commaseperated)。我该怎么做?
答案 0 :(得分:2)
您可以将group_concat
功能与group by
一起使用。
试试这个......
SELECT
users.identifier,
users.firstname,
users.lastname,
GROUP_CONCAT(CONCAT(user_licenses.type, ' - ', user_licenses.warnings) SEPARATOR ', ')
FROM users
INNER JOIN user_licenses ON users.identifier=user_licenses.owner;
GROUP BY
users.identifier, users.firstname, users.lastname
答案 1 :(得分:0)
试试这个,
SELECT users.identifier, users.firstname, users.lastname,
GROUP_CONCAT( TRIM( user_licenses.type ) ) AS typesOfLicenses,
GROUP_CONCAT( TRIM( user_licenses.warnings ) ) AS warningOfLicenses
FROM users
INNER JOIN user_licenses ON (users.identifier = user_licenses.owner)
GROUP BY users.identifier, users.firstname, users.lastname
如果user_licenses.warnings是一个字符列,它将会很好用。