你可能在尋找這樣的事情。
首先,讓我們創建一些測試數據:
create table course (id int primary key, name varchar(20));
insert into course (id, name) values
(1,'cooking'),
(2,'super hero'),
(3,'otaku');
create table knowledge (id int primary key, name varchar(30));
insert into knowledge (id, name) values
(4,'boil egg'),
(5,'toast bread'),
(6,'maintain secret identity'),
(7,'read');
create table courses_required_knowledges (id int primary key, course_id int, requiredknowledge_id int);
insert into courses_required_knowledges (id, course_id, requiredknowledge_id) values
(8,1,4),
(9,1,5),
(10,2,6),
(11,3,7);
create table user_info (id int primary key, name varchar(20));
insert into user_info (id, name) values
(12,'John Doe'),
(13,'Konata'),
(14,'Mega Mindy');
create table users_knowledge (id serial primary key, userInfo_id int, knowledge_id int);
insert into users_knowledge (userInfo_id, knowledge_id) values
(12,4),
(12,7),
(12,5),
(13,7),
(14,6),
(14,7),
(14,5);
查詢下方加入他們對記者的字段。
隨着用戶表交叉連接(全部到)所需的課程。
select
-- course.id as course_id,
-- coursereq.requiredknowledge_id,
-- user_info.id as user_id,
course.name as course,
reqknow.name as required_knowledge,
user_info.name as username,
(case when users_knowledge.id is null then 'N' else 'Y' end) as user_meets_requirement
from courses_required_knowledges as coursereq
full outer join user_info on (1=1)
left join users_knowledge
on (user_info.id = users_knowledge.userInfo_id and
coursereq.requiredknowledge_id = users_knowledge.knowledge_id)
left join knowledge as reqknow
on (coursereq.requiredknowledge_id = reqknow.id)
-- left join knowledge as usrknow
-- on (users_knowledge.knowledge_id = usrknow.id)
left join course
on (coursereq.course_id = course.id)
where users_knowledge.id is null
order by
course.name, reqknow.name, user_info.name;
這將給用戶錯過的要求註冊課程。
結果:
course required_knowledge username user_meets_requirement
cooking boil egg Konata N
cooking boil egg Mega Mindy N
cooking toast bread Konata N
super hero maintain secret identity John Doe N
super hero maintain secret identity Konata N
請顯示您到目前爲止所嘗試的內容。 – Serg
編輯你的問題,並提供樣本數據和期望的結果。另外,用您正在使用的數據庫標記問題。 –
我想,也許concat列值(group by)並比較它 –