douqian6315 2014-12-03 18:35
浏览 15
已采纳

SQL NOT查询返回错误的结果

I have 2 SQL tables. users contains users and registrants contains all the registrations done for an event. Given that I have the id of the event - I am successfully printing out those users that are registered for a specific event. However I want to print all the users that are NOT registered for the event and here I fail at producing the correct result. My query is as follows:

SELECT users.fName, users.lName, users.uid
FROM users, registrants
WHERE registrants.tourId = '$id' AND NOT registrants.pId = users.uid

The result of this is an array of 33 users printed out, although I have only 12, 3 of which are already registered for the event. Is the SELECT command wrong or I will need to dig into the php code, although I am pretty sure all the work there is correct.

  • 写回答

4条回答 默认 最新

  • dongqiyang3711 2014-12-03 18:46
    关注

    By specifying no JOIN syntax, but instead specifying a kind of inequality join in the WHERE clause, you are effectively asking SQL to find all combinations of users and registrants, with the additional filter criteria in the WHERE clause, hence the large number of rows.

    I believe the query you are looking for is more like this:

    SELECT users.fName, users.lName, users.uid
    FROM users
    WHERE users.uid NOT IN (
       SELECT registrants.pId 
       FROM registrants
       WHERE registrants.tourId = '$id');
    

    "Find all users, except those registered for tourId = '$id'"

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大