mysql选择第三个表中不存在的连接行

z6psavjg  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(332)

我很难创建一个sql查询来选择两个表的连接,而第三个表中不存在这种关系。
更具体地说,我试着用一个例子来解释。我有一个表成员、表和表成员。当一个成员在表单中插入一个答案时,它会保存在member\u form表中。表单可以是活动的,并且有一个截止日期。所以我想要的是为每个成员返回一个结果和他仍然没有填写的表格。但是表单必须是活动的,并且截止日期必须是例如2018-03-15。我不知道会员或表格的数量。所以我不能从select*中说成员id=x。这是需要发送一个提醒邮件给所有用户,还没有填写表格的具体日期。

member
id  |   name    |   email
--------------------------
1   |   Test    |   test@email.com
2   |   test2   |   test2@email.com
4   |   test4   |   test4@email.com
5   |   test5   |   test5@email.com
6   |   test6   |   test6@email.com
7   |   test7   |   test7@email.com

form
id  |   insert_date         |   deadline_date       |   active
---------------------------------------------------------------
1   |   2018-03-15 00:00:00 |   2018-03-15 00:00:00 |   1   
2   |   2018-02-10 00:00:00 |   2018-05-15 00:00:00 |   0   
3   |   2018-03-15 00:00:00 |   2018-03-15 00:00:00 |   1   
5   |   2018-03-15 00:00:00 |   2018-06-15 00:00:00 |   1   
6   |   2018-03-15 00:00:00 |   2018-05-15 00:00:00 |   1   
7   |   2018-03-15 00:00:00 |   2018-04-15 00:00:00 |   0       

member_form
member_id   |   form_id     |   answer
--------------------------------------
1           |   6           |   1
1           |   2           |   2
1           |   5           |   1
2           |   2           |   1
2           |   3           |   1
4           |   6           |   2
5           |   6           |   3
5           |   7           |   2
6           |   1           |   2
7           |   2           |   1

Result
member_id   |   name    |   email           |   form_id |   insert_date         |   deadline_date       |   active
-------------------------------------------------------------------------------------------------------------------
2           |   test2   |   test2@email.com |   6       |   2018-03-15 00:00:00 |   2018-05-15 00:00:00 |   1
6           |   test6   |   test6@email.com |   6       |   2018-03-15 00:00:00 |   2018-05-15 00:00:00 |   1
7           |   test7   |   test7@email.com |   6       |   2018-03-15 00:00:00 |   2018-05-15 00:00:00 |   1
jk9hmnmh

jk9hmnmh1#

试试这个

SELECT * FROM Member m, Form f 
WHERE CONCAT(m.id,':',f.id) NOT IN
(SELECT CONCAT(mf.member_id, ':', mf.form_id) FROM Member_form mf)
AND f.deadline_date = '2018-05-15' 
AND f.active = 1
rqdpfwrv

rqdpfwrv2#

SELECT * FROM form AS f , member AS m WHERE f.deadline_date = '2018-05-15 00:00:00' AND f.active = 1 and !exists(select * FROM member_form AS amf WHERE amf.member_id = am.id And amf.form_id = af.id);

相关问题