duanlinma5885 2016-06-22 10:27
浏览 58
已采纳

从一个表中选择不在另一个表中但具有特定条件的记录

I have three tables, let's call them offers, users and demands.

Table users
id | name
1      A
2      B
3      C

Table demands
id | id_user_fk
1         1
2         2
3         3

Table offers
id | id_demand_fk | id_user_fk
1         1             1
2         1             2
3         1             3
4         2             1
5         2             2
6         2             3

Here is my problem. The purpose is to assign users to demands in order to let them post offers. When I assign these users, I've a bootstrapTable that allows me to write in the offers table.

Here is the query I made to get the list of users :

SELECT u.id "
            . "FROM users u "
            . "LEFT JOIN offers o on o.id_user_fk = u.id "
            . "WHERE o.id_demand_fk <> " . $id . " OR u.id is null "
            . "GROUP BY u.id"

The purpose is to ONLY show users that are not already assigned to the offer (which is why I use an $id). Problem is, users 1, 2 and 3 are assigned to both demands 1 and 2, so when I open the view that should show users that can be assigned to demand 2, I do have users 1, 2 and 3 because they're assigned to demand 1. My query doesn't filter that, and I've no clue how to do it.

Thank you in advance

  • 写回答

3条回答 默认 最新

  • dongyou4411 2016-06-22 13:54
    关注

    Normally this is done with a LEFT OUTER JOIN (as you have done), but with the specific check done in the ON clause of the JOIN rather than just the WHERE clause. Then you check for a NULL field in the table that has been LEFT OUTER JOINed to check no match has been found:-

    SELECT u.id 
    FROM users u 
    LEFT OUTER JOIN offers o ON o.id_user_fk = u.id AND o.id_demand_fk = " . $id . "
    WHERE o.id IS NULL 
    

    An IN with a sub query is possible, but tends to perform badly as volumes rise.

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

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配