我有2张桌子。第一个称为refreshTimeout
,另一个称为subject
。
显然,主题表与注释具有一对多的关系。
以下是这些表的架构:
comment
:
subject
评论:
__________________________
| id | subject_id | title |
--------------------------
| 1 | 1 | health|
--------------------------
| 2 | 2 | sport |
---------------------------
| 3 | 5 | food |
---------------------------
我想检索所有user_id = 10且具有最大日期的subject_id表单主题表。我这种情况下的结果必须是这样的: 只有一条记录,它的subject_id = 1;
----------------------------------------
| 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:
$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)
未解决的问题是我如何过滤这些记录,以便检索user_id = 10的最新评论
答案 0 :(得分:0)
您不应该像以前那样对聚合进行分组。如果这是整个查询,则应按日期排序并将输出限制为第一行:
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
连接语法
答案 1 :(得分:0)
如果您想使用汇总,我认为子查询将以下面的方式为您提供帮助
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