MySql Left Join 记录 where is null with handling validUntil Row

MySql Left Join records where is null with handling validUntil Row

如何select特定用户未购买或不再有效的所有插件? 假设当前日期是 2017-03-02 17:00:00

表 1(用户):

+-----------+----------+
| id        | username |
+-----------+----------+
| 1         | Walter   |
| 2         | Hank     |
| 3         | John     |
+-----------+----------+

表 2(购买日志):

+-----------+----------+------------+---------------------+
| id        | idUsers  | idItems    | validUntil          |
+-----------+----------+------------+---------------------+
| 1         | 1        | 1          | 2016-03-02 14:15:47 |
| 2         | 1        | 1          | 2018-03-02 14:15:47 |
| 3         | 1        | 2          | 2016-03-02 14:15:47 |
| 4         | 2        | 1          | 2018-03-02 14:15:47 |
+-----------+----------+------------+---------------------+

表 3(插件):

+-----------+----------+
| id        | name     |
+-----------+----------+
| 1         | Foo      |
| 2         | Bar      |
| 3         | Lorem    |
+-----------+----------+

id 为 1 的用户的预期输出应该是:

+-----------+----------+
| id        | name     |
+-----------+----------+
| 2         | Bar      |
| 3         | Lorem    |
+-----------+----------+

请在此处查看 SQL Fiddle:http://sqlfiddle.com/#!9/16356

我遇到最多问题的地方是处理 leftJoin 中的 validUntil。 我想我必须在 left join 期间分组以仅踩踏最近的 validUntil 记录。也许使用 max(validUntil)?

此代码有效

http://sqlfiddle.com/#!9/16356/1/0

SELECT
C.ID AS 'ID',
C.NAME AS 'NAME'
FROM
(SELECT 
 A.id AS 'ID',A.name AS 'NAME',
 CASE 
 WHEN B.YY > '2017-03-02 17:00:00' THEN 0
 ELSE 1 END AS 'Tag'
 FROM
 addons AS A
 LEFT JOIN
 (SELECT idItems AS 'XX', MAX(validUntil) AS 'YY' 
  FROM 
  buyLog
  WHERE idUsers = 1 GROUP BY 1) AS B
  ON 
  A.id = B.XX) AS C
  WHERE 
  C.Tag = 1

我的感觉是,您的解释、数据集和期望的结果都不足以解释问题。以下查询产生了预期的结果,但也许这只是巧合...

SELECT a.* 
  FROM addons a
  LEFT
  JOIN buylog b
    ON b.iditems = a.id
   AND b.validuntil > NOW()
  LEFT
  JOIN users u
    ON u.id = b.idusers 
   AND u.id = 1
  WHERE b.validuntil IS NULL
    AND u.id IS NULL;