我需要将我的主查询与子查询结合起来:
当前查询(有效):
SELECT *,(SELECT SUM(shift_length)FROM overtime_list
WHERE overtime_list.user_ID = users.user_ID AND overtime_list.date > '$totalovertimedays') AS overtime_total FROM availability_list
JOIN users ON users.user_ID = availability_list.user_ID
JOIN stations ON users.station_ID` = stations.station_ID
WHERE availability_list.date = '$date' AND type = '$type'
ORDER BY overtime_total ASC
($date 和 $type 是 PHP 填写的 vars)
我想将其作为子查询插入的查询:
SELECT role_ID, GROUP_CONCAT(users_roles.role_ID) AS roles FROM users
JOIN users_roles ON users.user_ID = users_roles.user_ID
GROUP BY users.users_ID
我走了这么远 - 但我似乎无法让 GROUP BY 工作,所以它没有正确列出它们:
SELECT *,(SELECT SUM(shift_length)FROM overtime_list
WHERE overtime_list.user_ID = users.user_ID AND overtime_list.date > '$totalovertimedays') AS overtime_total FROM availability_list
JOIN users ON users.user_ID = availability_list.user_ID
JOIN `stations` ON `users`.`station_ID` = `stations`.`station_ID`,
(SELECT role_ID, GROUP_CONCAT(users_roles.role_ID separator ', ') AS roles FROM users JOIN users_roles ON users.user_ID = users_roles.user_ID GROUP BY users.user_ID) AS roles
WHERE availability_list.date = '$date' AND type = '$type'
ORDER BY overtime_total ASC
可用性列表表:
+----------+---------+
| user_ID | user |
+----------+---------+
| 1 | Smith |
+----------+---------+
| 2 | Jones |
+----------+---------+
| 3 | Greg |
+----------+---------+
overtime_list 表:
+----------+----------------+------------+
| date | shift_length | user_ID |
+----------+----------------+------------+
| 1/1/11 | 5 | 1 |
+----------+---------+------+------------+
| 1/2/11 | 5 | 2 |
+----------+---------+------+------------+
| 1/6/11 | 2 | 2 |
+----------+---------+------+------------+
| 1/8/11 | 5 | 1 |
+----------+---------+------+------------+
| 1/12/11 | 2 | 1 |
+----------+---------+------+------------+
users_roles 表:
+----------+---------+
| user_ID | roles |
+----------+---------+
| 1 | Admin |
+----------+---------+
| 2 | Staff |
+----------+---------+
| 2 | Admin |
+----------+---------+
| 2 | Super |
+----------+---------+
| 1 | Other |
+----------+---------+
所以结果是:
+----------+---------+----------------------------+------------------+
| user_ID | user | roles | overtime_total |
+----------+---------+----------------------------+------------------+
| 1 | Smith | Admin, Other | 12 |
+----------+---------+----------------------------+------------------+
| 2 | Jones | Staff, Admin, Super | 7 |
+----------+---------+----------------------------+------------------+
| 3 | Greg | | null (or zero) |
+----------+---------+----------------------------+------------------+