SELECT JOIN WHERE一条记录不存在

时间:2018-11-21 16:53:31

标签: mysql sql join

我有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

我需要获取记录1,aa,driver,该记录在第二个表中没有值“ active”的记录。 我的上一次尝试是这样的,但是我不确定是否接近我的需要,我的结果始终是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'
)

7 个答案:

答案 0 :(得分:1)

您可以按以下方式使用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'
)

答案 1 :(得分:0)

尝试一下(我想,并不是完全确定我了解这种联系):

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

left join返回第一个表的所有元素,无论它们在联接表中是否具有对应的记录。然后通过在t2.key is null子句中包含where,将其限制为仅存在于第一个表中的记录。

答案 2 :(得分:0)

只需左联接即可

    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

答案 3 :(得分:0)

这将起作用:

public class SimplePlatformController : MonoBehaviour
{

    // ...

    private int airJumpCount = 0; // Add this counter

    // ...

    // Update is called once per frame
    void Update()
    {
        grounded = Physics2D.Linecast(
                transform.position, groundCheck.position, 
                1 << LayerMask.NameToLayer("Ground"));

        if (grounded) airJumpCount = 0; // reset the counter when grounded

        if (Input.GetButtonDown("Jump") && grounded)
        {
            jump = true;  
        }

        // Only enter the air jump block if we still have more air jumps
        if ( Input.GetButtonDown("Jump") && !grounded && airJumpCount < 1) 
        {
            airJumpCount++;
            jump = true;  
        }
    }

    // ...
}

答案 4 :(得分:0)

  

我认为您的查询在这种情况下不起作用,请尝试   这个

 SELECT name FROM table1 
 JOIN table2 ON table1.id = 
 table2.parent_id where id not IN ( SELECT parent_id 
 FROM 
table2 WHERE `key` = 'active' )

答案 5 :(得分:0)

Select id,name,type from table1 
where id Not in
(Select 
 parent_id from table2 
 group by parent_id 
 having key= 
 'active') 
  

在这种情况下,最好避免加入,作为子查询   在这种情况下会很好。

答案 6 :(得分:-1)

选择t1.id,t1.name,t1.type,t2.key,t2.value 从table1 t1 JOIN table2 t2 ON t1.id = t2.parent_id 其中t2.key <>“活动”