检索其元记录中包含作者id且日期最新的所有记录

ljo96ir5  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(327)

我有两张table。第一个叫 subject 另一个打电话来 comment . 很明显,主题表和注解有一对多的关系。以下是这些表的架构: subject :

__________________________
| id | subject_id | title |
--------------------------
| 1  | 1          | health|
--------------------------
| 2  | 2          | sport |
---------------------------
| 3  | 5          | food  |
---------------------------

评论:

----------------------------------------
| id | user_id | subject_id | date      |
----------------------------------------
| 1  | 10      | 1          | 2018-07-04|
-----------------------------------------
| 2  | 9       | 1          | 2018-07-03|
-----------------------------------------
| 3  | 10      | 1          | 2018-07-02|
----------------------------------------

我想从subject表中检索所有用户id=10且最大日期为的subject id。在这种情况下,结果必须是这样的:只有一个记录,并且它的主题id=1;

$query = "SELECT subject_id FROM subject AS s, comment AS c WHERE 
           s.subject_id = c.subject_id AND c.user_id = 10
           GROUP BY MAX(c.date)

但不幸的是,它会根据与特定主题相关的注解数返回主题id:

首先,我可以选择所有评论与最大日期 SELECT * FROM comment GROUP BY subject_id HAVING max(date) 未回答的问题是我如何过滤这些记录以便检索用户id=10的最新评论

gwo2fgha

gwo2fgha1#

如果您想使用聚合,我认为子查询将帮助您在下面的方式

select subject_id from
(
select subject_id,max(date) from subject
inner join comment on subject.subject_id=comment.subject_id
where comment.user_id=10
group by subject_id
) as T
rta7y2nd

rta7y2nd2#

你不应该像以前那样分组。如果这是整个查询,则应按日期排序,并将输出限制在第一行:

select s.subject_id
from subject s
inner join comment c on
  s.subject_id = c.subject_id
where c.user_id = 10
order by c.date desc
limit 1

注意,我已经取代了老式的 , 连接语法 JOIN 关键字

相关问题