我有2个简单的表USERS和ORDERS,我想找到没有订单的用户。对于每个订单,我填充了一列userId
。我写了一个简单的查询,但她没有工作......
简单查询:
select id from USERS where id not in (select userId from ORDERS);
请注意,USERS.id
是VARCHAR
,如ORDERS.userId
。
有人可以解释一下:
> select count(distinct userId) from ORDERS;
+------------------------+
| count(distinct userId) |
+------------------------+
| 4261 |
+------------------------+
1 row in set (0.04 sec)
> select count(distinct id) from USERS;
+--------------------+
| count(distinct id) |
+--------------------+
| 14960 |
+--------------------+
1 row in set (0.00 sec)
> select id from USERS
> where id not in (select userId from ORDERS);
Empty set (0.47 sec)
我拥有的用户多于订购者的用户数量,但是设置很空!它必须是14960-4261 = 10699
但是当我这样做时:
> select count(*)
> from USERS left join ORDERS on ORDERS.userId=USERS.id
> where ifnull(ORDERS.userId,'')='';
+----------+
| count(*) |
+----------+
| 10700 |
+----------+
1 row in set (0.14 sec)
没问题! 1行只有一个错误(可能是由于null或0或空值...)
也许我累了但是之后......我觉得我对MySQL什么都不懂...... !!
答案 0 :(得分:2)
我不确定因为我无法访问这些表格, 但你可以尝试这个:Select by varchar column with IN() part in condition and int value returns all rows