簡體   English   中英

如何在特定列Mysql中查詢相同ID具有不同值的位置

[英]How to query where same id has different value in specific column Mysql

我有下面提到的表:

ID      Val1
1       AVD1R
1       ART1R
2       CFD4E
3       DER1R
3       DER1F

我想使用相同的Val1來獲取相同ID超過一次的那些記錄。

要求的輸出:

ID      Val1
1       AVD1R
1       ART1R
3       DER1R
3       DER1F

我試過了: select id, Val1 from Table1 where count(Val1)>1 group by id; 但這沒有用。

抱歉,我將答案更改為:

SELECT t1.* FROM Table1 t1
INNER JOIN Table1 t2 
  ON t1.id=t2.id AND t1.VAl1 <> t2.Val1;

樣品

MariaDB [bernd]> select * from Table1;
+----+-------+
| id | VAl1  |
+----+-------+
|  1 | AVD1R |
|  1 | ART1R |
|  2 | CFD4E |
|  3 | DER1R |
|  3 | DER1F |
+----+-------+
5 rows in set (0.00 sec)

MariaDB [bernd]> SELECT t1.* FROM Table1 t1
    -> INNER JOIN Table1 t2 ON t1.id=t2.id AND t1.VAl1 <> t2.Val1;
+----+-------+
| id | VAl1  |
+----+-------+
|  1 | ART1R |
|  1 | AVD1R |
|  3 | DER1F |
|  3 | DER1R |
+----+-------+
4 rows in set (0.00 sec)

MariaDB [bernd]> 
SELECT a.* FROM (
    SELECT ID, Val1, COUNT(*) AS Cn FROM Table1 GROUP BY ID, Val1) AS a
LEFT JOIN (
    SELECT ID, COUNT(*) AS Cn FROM Table1 GROUP BY ID
) AS b ON a.ID = b.ID
WHERE a.Cn <> b.Cn

我不知道其他的列是什么。

但是在SQL Server中:

select distinct a.id,val1 from
(
select id,val1
from different
)a
inner join
(
select id,count(id) as cnt
from different 
group by id
having count(*)>1
 ) b
  on  a.id=b.id

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM