选择多个唯一类别id的最新条目

gkl3eglg  于 2021-06-23  发布在  Mysql
关注(0)|答案(3)|浏览(409)
  1. Table Name: entries
  2. ID (int)
  3. rootID (int)
  4. categoryID (int)
  5. editDate (dateTime [ default null ])
  6. createdDate (dateTime [ default NOW() ])
  7. +--+--------+----------+---------------------+---------------------+
  8. |ID| rootID |categoryID| editDate | createdDate |
  9. +--+--------+----------+---------------------+---------------------+
  10. | 1| 1 | 1 | 2018-05-02 18:59:01 | 2018-04-01 18:52:37 |
  11. | 2| 1 | 1 | null | 2018-05-02 18:59:01 |
  12. | 3| 3 | 1 | 2018-06-10 19:32:01 | 2018-06-10 19:12:01 |
  13. | 4| 3 | 1 | 2018-07-11 18:52:01 | 2018-06-10 19:32:01 |
  14. | 5| 3 | 1 | null | 2018-07-11 18:52:01 |
  15. | 6| 6 | 1 | 2018-10-09 12:38:01 | 2018-10-09 12:27:01 |
  16. | 7| 6 | 1 | null | 2018-10-09 12:38:01 |
  17. | 8| 8 | 2 | 2018-11-09 08:12:11 | 2018-12-09 10:12:01 |
  18. | 9| 8 | 2 | null | 2018-11-09 08:12:11 |
  19. +--+--------+----------+---------------------+---------------------+

您好,我正在尝试从具有此结构的表中选择信息。我需要从所有rootid返回category 1中的所有行,但仅当editdate为null时,并且仅返回每个rootid中的min(createddate)。
我希望第二排、第五排和第七排的结果。但是,如果id[4]的editdate值要替换为null,则必须返回id 4,而不是rootid 3的5。
我一直在找一篇类似的文章,最近的一篇是:带where子句的sqlmin函数
我觉得我很接近我在那里找到的一个例子,但他们使用两个表,我只能使用这一个。以下是我正在尝试的:

  1. SELECT * FROM entries e WHERE e.categoryID=1 AND e.editDate is NULL AND e.createdDate in(SELECT min(createdDate) FROM entries)

但是,这只返回从第一个rootid开始的最早创建日期的一个条目。我很难理解这个查询,但我开始明白它是如何只引用一个条目的。
我要查找的是从categoryid=1中,找到每个不同rootid的id,其中最早的createddate行的编辑日期为空。如何更改此值以从每个根返回一个?谢谢大家抽出时间。今晚我将继续发布尝试的sql。

niknxzdl

niknxzdl1#

我想你想要这个:

  1. SELECT *
  2. FROM entries A
  3. WHERE Id IN (
  4. SELECT Id
  5. FROM entries B
  6. WHERE A.rootId = B.rootId
  7. AND A.categoryId = B.categoryId
  8. AND B.editDate IS NULL
  9. AND categoryId = 1
  10. AND A.createdDate = B.createdDate
  11. )
  12. GROUP BY rootId, categoryId
  13. HAVING createdDate = MIN(createdDate)
mzillmmw

mzillmmw2#

您的示例的问题是,它仅从整个表中选择createddate与最小createddate匹配的行。这就是select min(createddate)from entries的作用,只返回一个createddate。
我认为您需要做的是找到一种方法来为每个给定的rootid选择最小createddate。我会尝试这样的方法:

  1. SELECT *
  2. FROM entries A
  3. WHERE A.categoryId = 1
  4. AND A.editDate IS NULL
  5. AND A.createdDate = (SELECT MIN(B.createdDate)
  6. FROM entries B
  7. WHERE A.rootId = B.rootId
  8. AND B.categoryId = 1
  9. AND B.editDate IS NULL);

这样,您就可以从categoryid为1、editdate为null、createddate与categoryid=1、editdate为null的所有行的最小createddate相匹配的表中进行选择,并且rootid与外部查询正在查看的行相匹配。

vbopmzt1

vbopmzt13#

这对sql server和mysql都适用

  1. SELECT e.*
  2. FROM
  3. (
  4. SELECT rootID, MIN(CASE WHEN editDate IS NULL THEN ID ELSE NULL END) AS editDateId, MIN(createdDate) AS minCreatedDate
  5. FROM entries
  6. WHERE categoryID = 1
  7. GROUP BY rootID
  8. ) t
  9. JOIN entries e
  10. ON e.ID = (case when t.editDateId IS NOT NULL THEN editDateId END) OR
  11. (t.editDateId IS NULL AND createdDate = t.minCreatedDate)

相关问题