【问题标题】:selecting only newest row with specific value仅选择具有特定值的最新行
【发布时间】:2019-01-08 09:48:29
【问题描述】:

表:

person | borrow_date  | is_borrowed | SN | date        | id
1      | 2019-01-10...| 1           | 20 |2019-01-10...| 6
3      | 2019-01-09...| 3           | 10 |2019-01-09...| 5
1      | 2019-01-08...| 1           | 10 |2019-01-08...| 4
2      | 2019-01-08...| 1           | 10 |2019-01-08...| 3
1      | NULL         | 2           | 20 |2019-01-07...| 2
1      | NULL         | 2           | 10 |2019-01-07...| 1

我想要的输出是选择 "is_borrowed" 等于 1 并按 SN 分组的最新行,这样当使用 person=2 或 person=3 执行查询时,它将检索空集。而对于 person=1 它将返回两行。 想要的输出(其中 person=1):

person | borrow_date  | is_borrowed | SN | date         |id
1      | 2019-01-10...| 1           | 20 | 2019-01-10...|6
1      | 2019-01-08...| 1           | 10 | 2019-01-08...|4

想要的输出(其中 person=2):

EMPTY SET

想要的输出(其中 person=3):

EMPTY SET

这是我当前的查询,很遗憾它不起作用。

SELECT a.SN, a.is_borrowed,a.max(date) as date, a.person
FROM table a
INNER JOIN (SELECT SN, MAX(date) as date, osoba from table where person like 
"2"  group by SN) as b
ON a.SN=b.SN and a.date=b.date
WHERE a.person like "2" and a.is_borrowed=1

【问题讨论】:

  • 为什么要为第 2 个人返回一个空集?
  • 因为我只想检索最新的所有者(如果 is_borrowed = 1 则该人拥有该设备),因此人 2 不再拥有该设备,因为该设备有更新的记录(即由 SN 识别)在人员字段中具有不同的编号
  • 我在想SELECT * FROM t WHERE is_borrowed = 1 AND NOT EXISTS (SELECT 1 FROM t AS x WHERE sn = t.sn AND is_borrowed = 1 AND date > t.date) 但它返回三行,因为 3 和 4 具有相同的日期。
  • 我会尝试,因为我没有写更多的日期(小时等)。你没有包括 person 字段。

标签: mysql


【解决方案1】:

如果我从问题和您在该问题下所做的评论中正确理解了您,这是一种不指定人员的方法:

select * 
from TableName as p 
inner join (select max(borrow_date) as borrow_date,
                   SN 
            FROM TableName
            where is_borrowed = 1 
            group by SN) as p2
on p.borrow_date = p2.borrow_date and p.SN = p2.SN

这应该会为您提供您正在寻找的结果。这是demo

请注意,我必须更改表中的 borrowed_date 值,因为您的值包含小时和分钟,而我没有添加这些值。

您始终可以通过在连接后添加where 子句来为每个人指定它。

select p.person, 
       p.borrow_date, 
       p.is_borrowed, 
       p.SN, 
       p.date, 
       p.id 
from TableName as p 
inner join (select max(borrow_date) as borrow_date,
                   SN 
            FROM TableName
            where is_borrowed = 1 
            group by SN) as p2
on p.borrow_date = p2.borrow_date and p.SN = p2.SN
where p.person = '1'

输出:

person | borrow_date  | is_borrowed | SN |  date        | id
1      |  2019-01-10  |     1       | 20 |  2019-01-10  | 6   
1      |  2019-01-08  |     1       | 10 |  2019-01-08  | 4   

where p.person = '2'where p.person = '3' 将返回空集。

【讨论】:

  • 但是需要指定人,因为每个用户都必须知道他借用了哪些设备
  • SN 是设备号,对吧?如果是这样,那么此查询将为您提供每个人的当前 SN。您始终可以在查询中的 on 子句之后指定 where p.person = '1'
猜你喜欢
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-25
相关资源
最近更新 更多