mysql 最大值时的左连接

9cbw7uwe  于 2023-04-10  发布在  Mysql
关注(0)|答案(7)|浏览(139)

假设我有以下两个表:

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子句中是一个未知字段。
请建议我怎样才能实现我正在努力做的事情。
谢谢。

gpnt7bae

gpnt7bae1#

试试这样的方法:

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
)
bvjxkvbb

bvjxkvbb2#

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)
t3irkdon

t3irkdon3#

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)
yvfmudvl

yvfmudvl4#

您需要在student_story表的每一行添加一个自动且唯一的id。
然后你将区分它们。(假设studentstory.new_id)

select s.*, ss.*
from student s
left join student_story ss on ss.studentid = s.userid
where ss.new_id = ( select ss.new_id from student s
    group by dateline
    order by dateline desc
    limit 1
)
qfe3c7zg

qfe3c7zg5#

另一种方法是使用NOT EXISTS()条件生成LEFT JOIN。但是,如果每个学生有两个具有相同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)
hsvhsicv

hsvhsicv6#

这是一个相当冗长的查询示例,说明如何将具有相同ID(PK)的字段的最新[max()]版本连接起来,其中这些字段的最新版本可能在每个表中单独变化;例如来自表1的ID=1的最新版本,以匹配来自表2的ID=1的最新版本。

select td.task_id, td.duration, oda.task_id, oda.org_drtn_diff

from

(select * from task_dtl
where date_efctv = (select max(date_efctv) from task_dtl td where task_dtl.task_id=td.task_id)) td

left join
 
(select * from org_driven_actvty where date_efctv = (select max(date_efctv) from org_driven_actvty oda where org_driven_actvty.task_id=oda.task_id)) oda

on 

oda.task_id=td.task_id ;
lymnna71

lymnna717#

此连接应执行以下操作:

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
  • 我不确定,请评论结果 *

相关问题