简体   繁体   English

LEFT JOIN上的MAX()值

[英]MAX() value on a LEFT JOIN

I have 2 tables, one with a set of proposals and one with votes cast on the proposals, both joined with a unique ID. 我有2张桌子,一张桌子有一套提案,一张桌子对提案投了票,两张桌子都有唯一的ID。

The proposals table has a date field when the proposal was started, the votes have a date when the vote was cast. 提案表在提案开始时有一个日期字段,投票在投票中有一个日期。 The proposal is marked as "success" when enough votes are cast. 如果投票足够,则该提案将标记为“成功”。 I want to find out how many days it takes in average to close votes. 我想找出平均需要多少天才能完成投票。

My initial approach was to create a query that lists each proposal with the most recent vote through a left join: 我最初的方法是创建一个查询,该查询通过左连接列出具有最新投票的每个提案:

SELECT proposals.pr_id, DATEDIFF(MAX(proposals_votes.`date`), proposals.`date`)
FROM proposals
LEFT JOIN proposals_votes ON proposals.pr_id = proposals_votes.pr_id
WHERE STATUS = 'success'

The issue is that this returns only one line, which is a surprise to me. 问题是,这仅返回一行,这令我感到惊讶。 I would have thought the MAX is done on the LEFT JOIN table and not on the resulting table. 我本以为MAX是在LEFT JOIN表而不是结果表上完成的。

Is there a way to do this within the LEFT JOIN or do I need to do a sub-query? 是否可以在LEFT JOIN中执行此操作,还是需要执行子查询?

Use GROUP BY clause on pr_id to fetch no of days for each proposals 使用pr_id上的GROUP BY子句获取每个投标 的天数

Try this: 尝试这个:

SELECT p.pr_id, DATEDIFF(MAX(pv.`date`), p.`date`)
FROM proposals p 
LEFT JOIN proposals_votes pv ON p.pr_id = pv.pr_id
WHERE pv.status = 'success'
GROUP BY p.pr_id;

If you want to multiple line you should use GROUP BY because of aggregate function always return only one rows. 如果要多行,则应使用GROUP BY,因为聚合函数始终只返回一行。 You will get multiple rows result by GROUP BY parameter like GROUP BY proposals.pr_id. 您将通过GROUP BY参数(例如GROUP BY proposal.pr_id)获得多行结果。

SELECT 
    proposals.pr_id,
    DATEDIFF(MAX(proposals_votes.date),proposals.date)
FROM
    proposals
        LEFT JOIN
    proposals_votes ON proposals.pr_id = proposals_votes.pr_id
WHERE
    STATUS = 'success'
GROUP BY proposals.pr_id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM