相关数据库信息:我有两个表students
和links
,它们通过链接表links.student_id
中的外键关联,因此一个学生可以拥有多个链接。链接表有一个名为status
的列。
使用查询我想:
我设法为以上每一点写了查询:
// 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
但它似乎没有产生正确的结果。
任何帮助将不胜感激!感谢。
答案 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
它的工作原理如下: