简体   繁体   English

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

[英]MySQL select the condition only if row in column is duplicated

I want to select all LID which fulfill the selected LID. 我想选择所有满足所选LID的LID。 I have a table named LNZ for example like this: 我有一个名为LNZ的表,例如:

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

What I want is, to select all entries which contains the NID 1 and 4 in this case. 我想要的是在这种情况下选择包含NID 1和4的所有条目。 But it could be more than two NID selected. 但是可能会选择两个以上的NID。

For the NID 1 and 4 the output should be: 对于NID 1和NID 4,输出应为:

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

If I do this 如果我这样做

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

I get this wrong result: 我得到这个错误的结果:

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

It works with following SQL statement, but it isn't variable with the required NID 它可以与以下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;

My question now is... How can I change this statement, to make it variable with the number of selected NID? 我现在的问题是...如何更改此语句,以使其随所选NID的数量而变化?

Feel free to ask if you don't know what I mean. 随意问你是否不明白我的意思。

If you try 如果你试试

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
)

where in your language that you use to build the query you dynamically set the (1,2,4) to the values of NID you want and you set the count (based on the number of NIDs you want, in my example it is 3), it should work 在您用来构建查询的语言中,将(1,2,4)动态设置为所需的NID值,并设置计数(基于所需的NID数,在我的示例中为3) ),应该可以

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)

@NemanjaPerovic offered nice solution, this solution looks like it, difference is that you can count NID's here, instead of language/application level. @NemanjaPerovic提供了很好的解决方案,这个解决方案看起来像它,区别在于您可以在这里计算NID,而不是语言/应用程序级别。 Something like this: 像这样:

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) )
)

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

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