mysql在同一个表

时间:2015-07-30 14:12:45

标签: mysql

相关数据库信息:我有两个表studentslinks,它们通过链接表links.student_id中的外键关联,因此一个学生可以拥有多个链接。链接表有一个名为status的列。

使用查询我想:

  1. 选择相关链接表中没有条目的学生
  2. 选择具有相关链接的学生,但最近的链接不应具有有效状态
  3. 我设法为以上每一点写了查询:

    // 1. students with no links
    select s.id
    from students s
    left join links l
        on l.student_id = s.id
    where l.student_id is null
    

    // 2. students where last link is not complete
    select l2.student_id as id
    from links l1
    JOIN (
        SELECT MAX(id) as link_id, student_id, status
        FROM links
        where status != 'active'
        GROUP BY student_id
    ) l2 on l1.id = l2.link_id
    

    但理想情况下,这将写在一个查询中,我不确定这样做的正确方法是什么。我尝试使用这样的联盟:

    select students.name
    from students
    join (
        select s.id as id
        from students s
        left join links l
            on l.student_id = s.id
        where l.student_id is null
        UNION ALL
        select l2.student_id as id
        from links l1
        JOIN (
            SELECT MAX(id) as link_id, student_id, status
            FROM links
            where status != 'active'
            GROUP BY student_id
        ) l2 on l1.id = l2.link_id
    ) as s1 on s1.id = students.id
    

    但它似乎没有产生正确的结果。

    任何帮助将不胜感激!感谢。

1 个答案:

答案 0 :(得分:2)

这个应该这样做:

SELECT a.id
FROM students a
LEFT JOIN (
    SELECT student_id, max(id) AS id
    FROM links
    GROUP BY student_id
) b on a.id = b.student_id
LEFT JOIN links c ON c.id = b.id
WHERE c.status IS NULL 
      OR c.status != 'active'
GROUP BY a.id

它的工作原理如下:

  1. 抓住所有学生(a)
  2. 加入临时表(b),每个学生的最新链接由
  3. 组成
  4. 根据最新链接的ID
  5. 加入主链接表
  6. 仅保留没有链接的记录或链接状态未激活的记录