如何查询同一个id在特定列Mysql中具有不同值的位置

时间:2018-03-24 14:14:26

标签: mysql sql

我有下面提到的表:

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

我想要使用不同的ID获取同一Val1次多次的记录。

必需输出:

ID      Val1
1       AVD1R
1       ART1R
3       DER1R
3       DER1F

我试过这个: select id, Val1 from Table1 where count(Val1)>1 group by id;但它没有用。

3 个答案:

答案 0 :(得分:1)

抱歉,我已将答案更改为:

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

我不知道其他列是什么。

但在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