[英]How can I check if the same ID has different values in different rows?
I have the following table: 我有下表:
+----+----------+-------------------+
| ID | ID_CICLO | id_caratteristica |
+----+----------+-------------------+
| 1 | 72 | 2 |
+----+----------+-------------------+
| 2 | 72 | 3 |
+----+----------+-------------------+
| 3 | 73 | 2 |
+----+----------+-------------------+
| 4 | 73 | 4 |
+----+----------+-------------------+
| 9 | 3 | 2 |
+----+----------+-------------------+
| 10 | 3 | 4 |
+----+----------+-------------------+
And I want to extract all IDs that have an id_caratteristica = 2 and also equal to 4. 我想提取有id_caratteristica = 2, 也等于4所有的ID。
This is what I tried, but it is wrong because the And
operator only works on the same row. 这是我尝试过的方法,但这是错误的,因为And
运算符仅在同一行上工作。
SELECT * FROM caratteristiche_ciclo
WHERE id_caratteristica = 2
and id_caratteristica = 4
The result should be ID_CICLO {3, 73}
. 结果应为ID_CICLO {3, 73}
。 How can I achieve that? 我该如何实现?
You can approach this problem using conditional aggregation based filtering. 您可以使用基于条件聚合的过滤来解决此问题。 Firstly, get all the ID
where id_caratteristica IN(2,4)
. 首先,获取所有ID
,其中id_caratteristica IN(2,4)
。
Then, you can use HAVING
clause to filter out the ID having both the id_caratteristica
values: 然后,您可以使用HAVING
子句过滤出具有两个id_caratteristica
值的ID:
SELECT id
FROM caratteristiche_ciclo
WHERE id_caratteristica IN (2,4)
GROUP BY id
HAVING COUNT(DISTINCT id_caratteristica) = 2
For good performance, you can define the following Covering Index : (id, id_caratteristica)
为了获得良好的性能,您可以定义以下覆盖索引 : (id, id_caratteristica)
From you expected result, it looks like you are looking for id_ciclo, not id. 从预期结果来看,您似乎在寻找id_ciclo而不是id。
SELECT id_ciclo
FROM caratteristiche_ciclo
WHERE id_caratteristica IN (2,4)
GROUP BY id_ciclo
HAVING AVG(id_caratteristica) = 3
The query is: 查询是:
SELECT ID, ID_CICLO FROM caratteristiche_ciclo WHERE id_caratteristica IN(2, 4);
If you don't get the result you expect, your data is definitely not the same as the sample you posted. 如果您没有获得预期的结果,则您的数据肯定与您发布的样本不同。
Try this: 尝试这个:
SELECT T1.ID_CICLO FROM caratteristiche_ciclo T1
INNER JOIN (SELECT T2.ID_CICLO FROM caratteristiche_ciclo T2 WHERE T2.id_caratteristica = 4) Q ON Q.ID_CICLO = T1.ID_CICLO
WHERE T1.id_caratteristica = 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.