LEFT JOIN on Max Value

时间:2012-02-04 21:24:22

标签: mysql left-join

假设我有以下两个表:

STUDENT
studentid   lastname   firstname
1           Smith      John
2           Drew       Nancy

STUDENT_STORY
studentid   dateline   storyid   status
1           1328313600 10        2
1           1328313601 9         1
2           1328313602 14        2
2           1328313603 12        1

现在,我需要一个SQL查询,在学生故事表中选择每个学生以及该学生的最新故事。

我正在尝试这个:

SELECT s.*, ss.*
FROM student AS s
LEFT JOIN (
    SELECT *
    FROM student_story
    WHERE student_story.studentid = s.studentid
    ORDER BY dateline DESC LIMIT 1
) AS ss ON (ss.studentid = s.studentid)

但是,此查询不起作用。它抱怨s.studentid是子查询的where子句中的一个未知字段。

请建议我如何实现我的目标。

感谢。

6 个答案:

答案 0 :(得分:22)

尝试这样的事情:

SELECT
  s.*,
  ss.*
FROM
  student AS s
LEFT JOIN
  student_story AS ss
ON (ss.studentid = s.studentid)
WHERE ss.dateline = (
  SELECT
    MAX(dateline)
  FROM
    student_story AS ss2
  WHERE
    ss2.studentid = s.studentid
)

答案 1 :(得分:2)

SELECT s.*, ss.*
FROM student AS s
LEFT JOIN (

SELECT * FROM student_story    
ORDER BY dateline DESC LIMIT 1
) 
AS ss ON (ss.studentid = s.studentid)

答案 2 :(得分:1)

此联接应该这样做:

SELECT s.*, ss.*
FROM student_story AS ss
LEFT JOIN student AS s
    ON student_story.studentid = s.userid
GROUP BY ss.studentid

GROUP BY应占据最后一行,所以最后一个故事=最后一行,如果不起作用,请尝试:

GROUP BY ss.studentid, ss.dateline DESC

我不确定,请对结果发表评论

答案 3 :(得分:1)

SELECT 
    s.sale_id,
    s.created_at,
    p.created_at,
    DATEDIFF(p.created_at, s.created_at) AS days
FROM
    pos_sales s
        LEFT JOIN
    pos_payments p ON p.sale_id = s.sale_id
        AND
    p.created_at = (SELECT 
            MAX(p2.created_at)
        FROM
            pos_payments p2
        WHERE
            p2.sale_id = p.sale_id)

答案 4 :(得分:0)

您需要在student_story表格的每一行上添加自动且唯一的ID。

然后你会区分它们。 (假设studentstory.new_id)

The options argument allows you to customize the client with the following properties:

request: to override the request module.
httpClient: to provide your own http client that implements request(rurl, data, callback, exheaders, exoptions).

答案 5 :(得分:0)

另一种方法是使LEFT JOIN具有NOT EXISTS()条件。根据具体情况,这可以提供更多的灵活性;但是,如果每个学生有两个相同dateline的条目,它也会显示重复的结果:

SELECT s.*, ss.*
FROM student AS s
LEFT JOIN student_story AS ss ON ss.studentid = s.studentid AND NOT EXISTS
    (SELECT * FROM student_story AS ss2
     WHERE ss2.studentid = ss.studentid AND ss2.dateline > ss.dateline)