我正在加入3个表格,其中一个是users
保存相关人员的详细信息events
保存事件的详细信息invites
包含已发送的邀请详情和被邀请者的回应。
因为我没有每个人的电子邮件地址,所以不是每个人都会受到电子邮件的邀请。受邀请的所有人都会在invites
中排成Response
,Y
,N
或U
(是,否,未答复)。
联合表中的“响应”列可以有4个结果Y, U, NUll, N,
我想使用ORDER BY对ORDER中的表进行排序,但它不起作用。我仍然是 mysql 的新手,但我猜是因为WHERE
子句在完成JOIN
和NULL
值之前过滤掉了不相关的结果还不存在。
SELECT users.id, name, email, eventdate, response
FROM users
LEFT JOIN events
ON users.teamID=events.teamID
LEFT JOIN invites
ON events.eventID=invites.eventID
AND users.id=invites.id
WHERE users.teamID=:teamID
ORDER BY
eventdate DESC,
response='Y' DESC,
response='U' DESC,
response IS NULL DESC,
response='N' DESC
// users
+----+------+-------+--------+
| id | name | email | teamID |
+----+------+-------+--------+
| 1 | SM | NULL | 1 |
| 2 | CK | NULL | 1 |
| 3 | JG | NULL | 1 |
| 4 | DM | NULL | 1 |
+----+------+-------+--------+
// events
+---------+--------+------------+
| eventID | teamID | eventdate |
+---------+--------+------------+
| 1 | 1 | 2017-09-30 |
+---------+--------+------------+
// invites
+---------+----+----------+
| eventID | id | response |
+---------+----+----------+
| 1 | 1 | Y |
| 1 | 2 | N |
| 1 | 3 | U |
+---------+----+----------+
我想要实现的目标是什么?
+----+------+-------+------------+----------+
| id | name | email | eventdate | response |
+----+------+-------+------------+----------+
| 1 | SM | NULL | 2017-09-30 | Y |
| 3 | JG | NULL | 2017-09-30 | U |
| 4 | DM | NULL | 2017-09-30 | NULL |
| 2 | CK | NULL | 2017-09-30 | N |
+----+------+-------+------------+----------+
答案 0 :(得分:1)
您可能希望使用字段
来使用订单 SELECT id, name, email, eventdate, response
FROM users
LEFT JOIN events ON users.teamID=events.teamID
LEFT JOIN invites ON events.eventID=invites.eventID AND users.id=invites.id
WHERE TeamID=:TeamID
ORDER BY eventdate DESC, field( response, 'Y', 'U', 'N') DESC
或者如果您需要更直接的管理,可以在
时使用案例 SELECT id, name, email, eventdate, response
FROM users
LEFT JOIN events ON users.teamID=events.teamID
LEFT JOIN invites ON events.eventID=invites.eventID AND users.id=invites.id
WHERE TeamID=:TeamID
ORDER BY eventdate DESC, case when response = 'Y' then 100
when response = 'U' then 50
when response is null then 20
when response = 'N' then 10
else 0 end DESC
答案 1 :(得分:0)
在结果字段
中为order_by
创建一个字段
SELECT users.id, name, email, eventdate, response,
CASE response
WHEN 'Y' THEN 1
WHEN 'U' THEN 2
WHEN 'N' THEN 4
ELSE 3
END CASE as order_by
FROM users
LEFT JOIN events
ON users.teamID=events.teamID
LEFT JOIN invites
ON events.eventID=invites.eventID
AND users.id=invites.id
WHERE users.teamID=:teamID
ORDER BY
eventdate DESC,
order_by ASC