简体   繁体   English

SELECT JOIN WHERE一条记录不存在

[英]SELECT JOIN WHERE a record does not exist

I have 2 tables 我有2张桌子

id      name   type
1       aa     driver
2       bb     cyclist
3       cc     runner

parent_id      key      value
1              mobile   00299029
2              mobile   008772
2              active   1
3              mobile   09887
3              active   0

I need to get the record 1,aa,driver, the one that has not a record with value 'active' in the second table. 我需要获取记录1,aa,driver,该记录在第二张表中没有值'active'的记录。 My last try was something like this, but I'n not sure to be even a bit close to what I need, my result is always 0 records 我的上一次尝试是这样的,但是我不确定是否接近我的需要,我的结果始终是0条记录

SELECT t1.name as name
FROM table1 as t1
JOIN table2 as t2 ON t1.id = t2.parent_id
AND NOT EXISTS (
  SELECT * FROM table2
   WHERE key = 'active'
)

You can use NOT EXISTS as follows: 您可以按以下方式使用NOT EXISTS

select t1.name from table1 t1 
where not exists 
(
    select 1 from table2 t2 where t1.id = t2.parent_id  AND t2.key = 'active'
)

Try this (I think, not entirely sure I understand the linkage): 试试这个(我想,并不是完全确定我了解这种联系):

SELECT t1.name as name
FROM table1 as t1
LEFT JOIN table2 as t2 ON t1.id = t2.parent_id and t2.key = 'active' where t2.key is null

A left join returns all elements of the first table regardless of whether they have a corresponding record in the joined table. left join联接将返回第一个表的所有元素,无论它们在联接表中是否具有对应的记录。 By then including t2.key is null in the where clause, you limit it to records that only exist in the first table. 通过在where子句中包含t2.key is null ,可以将其限制为仅存在于第一个表中的记录。

Just a left join would do 只需左联接即可

    SELECT t1.name as name
     FROM table1 as t1
LEFT JOIN table2 as t2 
       ON t1.id = t2.parent_id
      AND t2.key = 'active'
    WHERE t2.key IS NULL

This will work: 这将起作用:

SELECT t1.name as name
FROM table1 as t1
JOIN table2 as t2 ON t1.id = t2.parent_id
AND t2.key  not like '%active%'

I think Your query is not working in this case, please try this 我认为您的查询在这种情况下不起作用,请尝试

 SELECT name FROM table1 
 JOIN table2 ON table1.id = 
 table2.parent_id where id not IN ( SELECT parent_id 
 FROM 
table2 WHERE `key` = 'active' )
Select id,name,type from table1 
where id Not in
(Select 
 parent_id from table2 
 group by parent_id 
 having key= 
 'active') 

Better avoid join in this case I would say as subquery would do good in this case. 在这种情况下,最好避免加入联接,因为子查询在这种情况下会很好。

从表1选择t1.id,t1.name,t1.type,t2.key,t2.value t1加入JOIN table2 t2开启t1.id = t2.parent_id其中t2.key <>'active'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM