我正在尝试创建一个在我当前查询中添加...
elif (score == "quit")
...
作为新列的查询,首先是我的表格:
GROUP_CONCAT
基本上,我想要一个查询,它获取所有用户(显示在表中)的自定义列,该列显示附加到该用户的所有移位(如果没有移位附加到显然有空结果)
这是我到目前为止所做的查询:
Users table
+----+----------+--------------+
| id | username | date_created |
+----+----------+--------------+
| 1 | user1 | 2000-03-16 |
| 2 | user2 | 2001-05-14 |
| 3 | user3 | 2002-01-13 |
| 4 | user4 | 2003-03-14 |
+----+----------+--------------+
Shifts table
+----+------------+--------------+
| id | shift_name | date_created |
+----+------------+--------------+
| 1 | shift1 | 2002-05-10 |
| 2 | shift2 | 2002-07-11 |
| 3 | shift3 | 2002-09-23 |
+----+------------+--------------+
Accounts table
+----+--------------+--------------+
| id | account_name | date_created |
+----+--------------+--------------+
| 1 | account1 | 2001-05-01 |
| 2 | account2 | 2001-05-02 |
| 3 | account3 | 2001-05-03 |
+----+--------------+--------------+
Shift Mapping table
+----+---------+----------+------------+
| id | user_id | shift_id | account_id |
+----+---------+----------+------------+
| 1 | 1 | 1 | 1 |
| 2 | 1 | 2 | 2 |
| 3 | 3 | 1 | 1 |
+----+---------+----------+------------+
现在使用转移附加的用户没有问题,我的问题是没有转移附加的用户只返回由SELECT users.id AS user_id, users.username, users.date_created,
GROUP_CONCAT(DISTINCT (t.shift_name)) AS shifts
FROM (`users`)
LEFT JOIN
(SELECT s.shift_name, sm.user_id FROM shift_map sm
LEFT JOIN shifts s ON sm.shift_id = s.id) t
ON users.id = t.user_id
GROUP BY user_id
ORDER BY `users`.`date_created` DESC;
引起的1结果我如何排除用户GROUP BY没有转换,或者如何返回所有附加轮班且没有附加班次的用户?感谢。
更新
以下是我想看到的示例结果:
GROUP BY user_id
我的查询中的问题是它只显示了一个空转的用户。
答案 0 :(得分:0)
SELECT users.id AS user_id, users.username, users.date_created,
GROUP_CONCAT(DISTINCT (t.shift_name)) AS shifts
FROM (`users`)
LEFT JOIN
(SELECT s.shift_name, sm.user_id FROM mapping sm
LEFT JOIN shifts s ON sm.shift_id = s.id) t
ON users.id = t.user_id
GROUP BY username
ORDER BY user_id
+---------+----------+--------------+---------------+
| user_id | username | date_created | shifts |
+---------+----------+--------------+---------------+
| 1 | user1 | 2000-03-16 | shift1,shift2 |
| 2 | user2 | 2001-03-16 | NULL |
| 3 | user3 | 2002-03-16 | shift1 |
| 4 | user4 | 2003-03-16 | NULL |
+---------+----------+--------------+---------------+
答案 1 :(得分:0)
我的坏,我可以使用简单的LEFT JOIN
:
SELECT users.id AS user_id, users.username, users.date_created,
GROUP_CONCAT(DISTINCT (shift.shift_name)) AS shifts
FROM (`users`)
LEFT JOIN shifts_map ON users.id = shifts_map.user_id
LEFT JOIN shifts ON shifts_map.shift_id = shift.id
GROUP BY user_id
ORDER BY `users`.`date_created` DESC;
我只是使查询复杂化,忘了简单的LEFT JOIN
可以解决问题。感谢。