如何在mysql select/join查询中获取每个名称的最新值?

baubqpgj  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(301)

我有一个生成记录列表的sql查询:

SELECT users.uid, users.name, times.entrytype, times.transactionid FROM users 
JOIN cards ON cards.eid = users.uid
JOIN times ON cards.cardid = times.cardid
WHERE users.active = true
AND cards.active = true
AND times.date = "2018-10-25"
ORDER BY users.name ASC, times.transactionid DESC

举个例子:

1   Joe Bloggs  false   9
1   Joe Bloggs  true    8
1   Joe Bloggs  false   7
1   Joe Bloggs  true    6
1   Joe Bloggs  false   5
1   Joe Bloggs  true    4
3   John Doe    true    10
2   Mary Jane   true    3
2   Mary Jane   false   2
2   Mary Jane   true    1

我正在试图找到一种方法来筛选这个列表,以便只获取每个人的最新(最大时间.transactionid值)条目。重要的值是每个名称的最新times.entrytype。
我希望结果是:

1   Joe Bloggs  false   9
3   John Doe    true    10
2   Mary Jane   true    3

我尝试按名称分组,但没有返回最新的times.entrytype(可能是最早的?)
我知道postgresql的distinct on,但这是mysql。
我也知道这似乎是一种常见的sql查询模式,但通过查看其他示例,我不太清楚它应该如何工作:/
编辑:

CREATE TABLE users (
    uid int,
    name varchar(32),
    active Boolean
);
CREATE TABLE cards (
    eid int,
    cardid int,
    active Boolean
);
CREATE TABLE times (
    cardid int,
    date varchar(16),
    transactionid int,
    entrytype Boolean
);
INSERT INTO users (uid, name, active) VALUES 
( 1, "Joe Bloggs", 1),
( 2, "Mary Jane", 1),
( 3, "John Doe", 1),
( 4, "Bod Dylan", 0);

INSERT INTO cards (eid, cardid, active) VALUES 
( 1, 10, 1),
( 2, 11, 1),
( 3, 12, 1),
( 4, 13, 0);

INSERT INTO times (cardid, date, transactionid, entrytype) VALUES 
( 11, "2018-10-25", 1, 1),
( 11, "2018-10-25", 2, 0),
( 11, "2018-10-25", 3, 1),
( 10, "2018-10-25", 4, 1),
( 10, "2018-10-25", 5, 0),
( 10, "2018-10-25", 6, 1),
( 10, "2018-10-25", 7, 0),
( 10, "2018-10-25", 8, 1),
( 10, "2018-10-25", 9, 0),
( 12, "2018-10-25", 10, 1);

sql fiddle链接:http://sqlfiddle.com/#!9/6b0f0be/1/0

zujrkrfu

zujrkrfu1#

在派生表中,确定 transactionid 对于特定的 uid . 你也可以改变你的位置 Where 此子选择查询的条件。
现在,将这个结果集连接回主表。
对于mysql版本8.0.2及更高版本,可以使用带有 Row_Number() .
尝试以下查询:

SELECT users.uid, 
       users.name, 
       times.entrytype, 
       times.transactionid 
FROM 
  (SELECT u1.uid, 
          MAX(t1.transactionid) AS max_transactionid 
   FROM users AS u1 
   JOIN cards AS c1 ON c1.eid = u1.uid 
   JOIN times AS t1 ON t1.cardid = c1.cardid 
   WHERE u1.active = true AND 
         c1.active = true AND 
         t1.date = '2018-10-25'
   GROUP BY u1.uid
  ) AS dt
JOIN users ON users.uid = dt.uid 
JOIN times ON times.transactionid = dt.max_transactionid
ORDER BY users.name ASC, 
         times.transactionid DESC

结果:

| uid | name       | entrytype | transactionid |
| --- | ---------- | --------- | ------------- |
| 1   | Joe Bloggs | 0         | 9             |
| 3   | John Doe   | 1         | 10            |
| 2   | Mary Jane  | 1         | 3             |

db fiddle视图

相关问题