根据另一个表Linq的特定值从一个表中选择值
本文关键字:一个 选择 Linq 另一个 | 更新日期: 2023-09-27 18:03:14
我有两个表:
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)
- 或if记录存在,则所有必须的状态等于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的Location被忽略了,因为它在Tasks表中有一些行状态不是1。
- Location with user_id = 3 was selected因为Tasks表中的所有行都有status = 1
- Location with user_id = 4 was selected因为Tasks表中没有user_id = 4的行
看看你的需求可以是这样的
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);
你的条件相当于说在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 exists
而不是not in
,因为如果user_id
在tasks
中是NULL
, not in
将过滤掉所有行。
使用没有子LEFT JOIN
的SELECT
:
SELECT
l.id,
l.user_id,
l.latitude,
l.longitude
FROM
Location l
LEFT JOIN Task t
ON l.user_id = t.user_id
WHERE
t.id IS NULL /* No record in tasks table */
OR (t.id IS NOT NULL AND l.status = 1) /* if records exists then all of them must have status equals to 1 */