mysql'ORDER BY'使用NO Values加入了列

时间:2017-09-01 14:53:34

标签: mysql sql-order-by

我正在加入3个表格,其中一个是users保存相关人员的详细信息events保存事件的详细信息invites包含已发送的邀请详情和被邀请者的回应。

因为我没有每个人的电子邮件地址,所以不是每个人都会受到电子邮件的邀请。受邀请的所有人都会在invites中排成ResponseYNU(是,否,未答复)。

联合表中的“响应”列可以有4个结果Y, U, NUll, N,

我想使用ORDER BY对ORDER中的表进行排序,但它不起作用。我仍然是 mysql 的新手,但我猜是因为WHERE子句在完成JOINNULL值之前过滤掉了不相关的结果还不存在。

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        |
+----+------+-------+------------+----------+

2 个答案:

答案 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