我在创建一个sql查询时遇到了困难,该查询选择了第二个表中不存在关系的2个表的连接。
更具体地说,我试着用一个例子来解释它。 我有一个表成员,表单和member_form。 当成员在表单中插入答案时,它将保存在member_form表中。 表格可以是活动的,并有截止日期。 所以我想要的是返回每个成员的结果和他仍未填写的表格。但表格必须是活动的,截止日期必须是例如2018-03-15。我不知道会员或表格的数量。所以我不能说select * where member 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
答案 0 :(得分:0)
试试这个
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
答案 1 :(得分:0)
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);