如何通过排除第二个表中的值来从一个表中选择值

时间:2018-02-02 02:29:36

标签: mysql sql mysql-workbench

以下是样本表。问题是如何从用户表中选择dtmemberID仅用于用户处于活动状态且未进行任何付款的日期?

我尝试过使用Except,但这似乎不起作用。

任何帮助都将不胜感激。

付款表(在这些日期付款的用户)

enter image description here

用户表(在这些日期有效的用户) enter image description here

4 个答案:

答案 0 :(得分:2)

在这种情况下你可以使用左连接,不存在,不存在,但我使用左连接

给出解决方案
[{
    "no": "1",
    "location": "Acheh Baru",
    "postcode": "32000",
    "postOffice": "Sitiawan",
    "state": "Perak"
}, {
    "no": "2",
    "location": "Akauntan Negeri",
    "postcode": "30594",
    "postOffice": "Ipoh",
    "state": "Perak"
}, {
    "no": "3",
    "location": "Alor Kechor",
    "postcode": "32800",
    "postOffice": "Parit",
    "state": "Perak"
}]

答案 1 :(得分:1)

我认为这个SQL符合您的要求:

Select u.memberID, u.Dt from Users u left join Payments p 
 on u.memberID = p.memberID
  and u.Dt = p.Dt
where p.amount is null;

答案 2 :(得分:0)

我认为这只是一个not exists或类似的查询:

select u.*
from users u
where not exists (select 1 from payments p where p.memberid = m.memberid);

答案 3 :(得分:0)

我们可以像这样使用LEFT OUTER JOIN

SELECT u.dt, u.memberID
FROM User u
LEFT OUTER JOIN Payments p ON p.dt = u.dt AND u.memberID = p.memberID
WHERE 
  p.amount IS NULL
ORDER BY u.dt, u.memberID

结果:

|         dt | memberID |
|------------|----------|
| 2018-01-01 |        5 |
| 2018-01-02 |        3 |
| 2018-01-02 |        4 |
| 2018-01-03 |        4 |
| 2018-01-03 |        5 |
| 2018-01-04 |        2 |
| 2018-01-06 |        1 |
| 2018-01-06 |        2 |
| 2018-01-06 |        6 |
| 2018-01-07 |        3 |
| 2018-01-07 |        4 |