根据另一个表Linq的特定值从一个表中选择值

时间:2016-08-19 19:36:17

标签: c# sql sql-server linq

我有两张桌子:

            Location
 id  | user_id | latitude | longitude|
  1  |    2    | 11.32323 | 11.32323 |
  2  |    3    | 12.32323 | 12.32323 | 
  3  |    4    | 21.32323 | 12.32323 |
           Task
 id  | user_id | status |
  1  |    2    |   0    |
  2  |    2    |   1    |
  3  |    2    |   0    |
  4  |    2    |   2    |
  5  |    2    |   1    |
  6  |    2    |   0    |
  7  |    3    |   1    |
  8  |    3    |   1    |
  9  |    3    |   1    |

我想从用户拥有的位置表中选择所有行

  • 任务表中没有记录(例如user_id = 4)
  • 或者如果记录 然后,所有必须状态等于1 (例如user_id) = 3)

在上面的示例中,不应选择user_id = 2,因为它在Tasks表中的行的状态不是1。

我对SQL和LINQ不是很熟悉所以任何帮助都会受到赞赏。

这是预期的结果:

            Result
 id  | user_id | latitude | longitude|
  2  |    3    | 12.32323 | 12.32323 | 
  3  |    4    | 21.32323 | 12.32323 |
  • user_id = 2的位置被忽略,因为它在Tasks表中有一些行,状态不是1。
  • user_id = 3的位置已选中,因为Tasks表中的所有行的状态均为=。
  • user_id = 4的位置已选中,因为在Tasks表中没有user_id = 4的行。

3 个答案:

答案 0 :(得分:1)

看着你的要求可能是这个

select * from location 
where user_id not in (select distinct user_id from task )
or user_id not in  (select distinct user_id from  task where status != 1);

答案 1 :(得分:1)

您的条件相当于说task中不存在非“1”值。我会把它写成:

select l.*
from location l
where not exists (select 1 from tasks where t.user_id = l.user_id and t.status = 1);

我更喜欢not existsnot in,因为如果not in user_id NULL tasks Uncaught TypeError: getState is not a functionapplyMiddleware(reduxImmutableStateInvariant)会过滤掉所有行1}}。

答案 2 :(得分:0)

使用LEFT JOIN而不使用子{ - 1}}

SELECT
相关问题