简体   繁体   English

查找具有相同列值而不是另一列值的行

[英]Find rows that have one column value same but not the other

I have a table structure like this: 我有这样的表结构:

ProductId | Parentid | Name

1 | 1 | Abc

2 | 1 | Abc

3 | 2 | Xyz

4 | 3 | Xyz

5 | 3 | Abc

I need a query which finds such rows which have parentid as the same as the other rows but different name than the other. 我需要一个查询来查找这样的行,这些行的parentid与其他行相同但名称不同于另一行。

For an example: Query should fetch below result, because parentid is same for both rows but name is not the same. 例如:查询应该获取下面的结果,因为两个行的parentid相同但名称不相同。

4 | 3 | Xyz

5 | 3 | Abc

Can somebody help forming the query? 有人可以帮助形成查询吗?

One way is this: 一种方法是:

SELECT ProductId, ParentId, Name
FROM mytable 
WHERE ParentId IN (
  SELECT Parentid
  FROM mytable
  GROUP BY Parentid
  HAVING MIN(Name) <> MAX(Name))

SQL Fiddle Demo SQL小提琴演示

You can alternatively use INNER JOIN : 您也可以使用INNER JOIN

SELECT ProductId, m.ParentId, Name
FROM mytable m
INNER JOIN (SELECT Parentid
            FROM mytable
            GROUP BY Parentid
            HAVING MIN(Name) <> MAX(Name)) t
ON m.ParentId = t.ParentId            

SQL Fiddle Demo SQL小提琴演示

As a final note, if you want all values in Name column to be distinct, then you have to use the following HAVING clause: 最后要注意的是,如果您希望Name列中的所有值都是不同的,那么您必须使用以下HAVING子句:

HAVING COUNT(*) > 1  AND COUNT(DISTINCT Name) = COUNT(*)

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

相关问题 在 MySQL 中的列上查找具有相同值的行 - Find rows that have the same value on a column in MySQL MySQL:查找具有相同值的行数 - Mysql: find number of rows which have same value one-after-other 如何查询具有第v.2列之一相同值的行中具有最高列值的行 - How to query for rows that have highest column value among rows that have same value for one of the columns v.2 查找具有相同列值的行 - Find rows with same value of a column 根据其他列值返回具有相同列值的所有行 - Returns all rows which have same column value based on other column value 根据不同列的行之一上的值返回具有相同 id 的所有行 - Return all rows that have the same id based on a value on one of the rows of a different column mySQL:我可以添加一个计算列,其中包含具有相同共享值的所有其他行的总和吗 - mySQL: Can I add a calculated column with the sum of all other rows that have that same shared value 如何查找具有一列值相同的多行并添加到一行并设置为vaadin网格 - how to find muliple rows which has one column value same and add to one row and set to vaadin grid MySql在列中查找具有相同值的多个行 - MySql find multiple rows with same value in a column SQL查询以查找某列值等于同一行中其他两列之和的行 - SQL query to find rows where a column value is equal to the sum of tow other columns in the same row
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM