Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select rows having 2 columns equal value

Tags:

sql

Consider following table

C1    || C2  || C3  || C4
--------------------------
1     || a   || b   || 1
2     || a   || b   || 4
3     || b   || d   || 2
4     || b   || d   || 2

Question 1: Select all rows in which Column C2 , C3, C4 have equal values e.g. select row 3 and row 4 in above example.

Question 2 : Select all rows in which C4 column has duplicates e.g. C4 has value 2 in row 3 and row 4, so select row 3 and 4.

like image 929
Rohit Avatar asked Aug 16 '11 10:08

Rohit


People also ask

How do I check if two columns match in SQL?

Here's the generic SQL query to two compare columns (column1, column2) in a table (table1). mysql> select * from table1 where column1 not in (select column2 from table1); In the above query, update table1, column1 and column2 as per your requirement.

How do you SELECT two columns in query?

To select multiple columns from a table, simply separate the column names with commas! For example, this query selects two columns, name and birthdate , from the people table: SELECT name, birthdate FROM people; Sometimes, you may want to select all columns from a table.

How do I compare two columns in the same table in SQL?

Comparison of columns in the same table is possible with the help of joins. Here we are comparing all the customers that are in the same city using the self join in SQL. Self-join is a regular join where a table is joined by itself. Similarly, a table may be joined with left join, right join, inner join, and full join.


4 Answers

Question 1 query:

SELECT ta.C1
      ,ta.C2
      ,ta.C3
      ,ta.C4
FROM [TableA] ta
WHERE (SELECT COUNT(*)
       FROM [TableA] ta2
       WHERE ta.C2=ta2.C2
       AND ta.C3=ta2.C3
       AND ta.C4=ta2.C4)>1
like image 149
Curtis Avatar answered Oct 02 '22 00:10

Curtis


Actually this would go faster in most of cases:

SELECT *
FROM table ta1
JOIN table ta2 on ta1.id != ta2.id
WHERE ta1.c2 = ta2.c2 and ta1.c3 = ta2.c3 and ta1.c4 = ta2.c4

You join on different rows which have the same values. I think it should work. Correct me if I'm wrong.

like image 36
dgmora Avatar answered Oct 02 '22 01:10

dgmora


Select * from tablename t1, tablename t2, tablename t3 
where t1.C1 = t2.c2 and t2.c2 = t3.c3 

Seems like this will work. Though does not seems like an efficient way.

like image 2
Rohit Avatar answered Oct 02 '22 01:10

Rohit


SELECT *
FROM my_table
WHERE column_a <=> column_b AND column_a <=> column_c
like image 2
jsHate Avatar answered Oct 02 '22 01:10

jsHate