MySQL仅在列中的行重复时才选择条件

时间:2017-05-17 13:05:34

标签: mysql sql database

我想选择满足所选LID的所有LID。我有一个名为LNZ的表,例如:

+------------+
|    LNZ     |
+-----+------+
| NID |  LID |
+-----+------+
|  1  |    1 |
|  1  |    2 |
|  1  |    3 |
|  2  |    1 |
|  2  |    3 |
|  3  |    1 |
|  4  |    1 |
|  4  |    2 |
+-----+-------+ 

我想要的是,在这种情况下选择包含NID 1和4的所有条目。但它可能超过两个NID被选中。

对于NID 1和4,输出应为:

+------------+
|    LNZ     |
+-----+------+
| NID |  LID |
+-----+------+
|  1  |    1 |
|  1  |    2 |
|  4  |    1 |
|  4  |    2 |
+-----+-------+ 

如果我这样做

SELECT  NID, LID
FROM    lnz
WHERE   NID = 1 OR NID = 4;

我得到了错误的结果:

+------------+
|    LNZ     |
+-----+------+
| NID |  LID |
+-----+------+
|  1  |    1 |
|  1  |    2 |
|  1  |    3 |
|  4  |    1 |
|  4  |    2 |
+-----+-------+ 

它适用于以下SQL语句,但它不具有所需的NID

SELECT T1.NID, T1.LID
FROM LNZ AS T1
JOIN LNZ AS T2 ON T1.LID = T2.LID
WHERE T1.NID = 1 AND T2.NID = 4
   OR T2.NID = 1 AND T1.NID = 4;

我现在的问题是......如何更改此声明,使其与所选NID的数量一起变化?

随时问你是否不知道我的意思。

3 个答案:

答案 0 :(得分:2)

如果您尝试

SELECT * FROM LNZ
WHERE NID IN (1,2,4)
AND LID IN (
    select LID from LNZ
    WHERE NID IN (1,2,4)
    GROUP BY LID
    HAVING COUNT(*) = 3
)

在您用于构建查询的语言中,您动态地将(1,2,4)设置为您想要的NID值并设置计数(基于您想要的NID数量,在我的示例中)它是3),它应该工作

答案 1 :(得分:0)

SELECT  T1.NID, T1.LID
FROM    LNZ AS T1
    JOIN (SELECT  LID
          FROM    lnz
          WHERE   NID = 1 OR NID = 4
          group by lid
          having count(*)>1) sub ON t1.lid=sub.lid
WHERE   (T1.NID = 1 OR T1.NID = 4)

答案 2 :(得分:0)

@NemanjaPerovic提供了很好的解决方案,这个解决方案看起来很像,不同的是你可以在这里计算NID,而不是语言/应用程序级别。像这样:

select * from LNZ 
where NID in(1,2,4)
and
lid in(
    select lid from LNZ 
    where NID in(1,2,4)  
    group by lid
    having count(*) = (select count(distinct NID) from LNZ where NID in(1,2,4) )
)