查询以识别没有特定值的记录

时间:2017-01-27 18:20:25

标签: sql db2

我有一个数据表,看起来像这样:

ID Num | Code
-------------
   1   |   A
   1   |   B
   1   |   C
   1   |   D
   2   |   A
   2   |   B
   3   |   A
   3   |   B
   3   |   D
   4   |   B
   5   |   A
   5   |   B
   5   |   E

我需要能够编写一个SQL查询来向我显示所有没有与之关联的代码C或D的ID号。 (在此示例中将是ID号码2,4和5)。

提前感谢您提供的任何帮助!

4 个答案:

答案 0 :(得分:1)

我会使用NOT IN:

void Graphics::UpdateLight() {
    short radius = 65; // 265 on the pictures

    int x = m_game->GetPlayer()->GetSprite()->getPosition().x + CASE_LEN / 2; // Setting on the middle of the player sprite (CASE_LEN is a const which contains the size of a case (here 32))
    int y = HEIGHT - (m_game->GetPlayer()->GetSprite()->getPosition().y + CASE_LEN / 2); // (the "HEIGHT -" part was set because it seems that y = 0 is on the bottom of the texture for GLSL)

    sf::Vector3f shaderLight;
    shaderLight.x = x;
    shaderLight.y = y;
    shaderLight.z = radius;

    m_lightShader.setParameter("light", shaderLight);
}

答案 1 :(得分:1)

我喜欢使用group byhaving来解决此类问题:

select id_num
from t
group by id_num
having sum(case when code in ('C', 'D') then 1 else 0 end) = 0;

答案 2 :(得分:0)

你可以使用'not exists'(通常更有效率)

SELECT DISTINCT ID_Num
FROM yourtable f1
WHERE not exists
(
    SELECT * FROM yourtable f2 
    WHERE f2.code in ('C', 'D') and f2.ID_Num=f1.ID_Num
)

答案 3 :(得分:0)

你可以使用'left outer join lateral'并且不使用这样的行:

{{1}}