I Have a table named contacts
with fields
+-----+------------+-----------+
| id | first_name | last_name |
+-----+------------+-----------+
I want to display all duplicates based on first_name
and (/ or) last_name
, e.g:
+----+------------+-----------+
| id | first_name | last_name |
+----+------------+-----------+
| 1 | mukta | chourishi |
| 2 | mukta | chourishi |
| 3 | mukta | john |
| 4 | carl | thomas |
+----+------------+-----------+
If searched on just first_name
it should return:
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
+----+
But if searched on both first_name
and last_name
should return:
+----+
| id |
+----+
| 1 |
| 2 |
+----+
and you write sql function which takes two parameters firstname and lastname and inside the functions you write your conditions if lastname=null find duplicates for firstname, and if firstname is null, find duplicates for the lastname, and so on so forth
the statemnets inside the conditions is
One way to achieve your result is using nested query and having clause: In inner query select those having count more then one, and in outer query select id:
Check following example for single column selection criteria:
Create table:
Insert tuple:
The result you need:
[ANSWER]
But as if you selection criteria is on the basis of more than one columns then you can make use of JOIN.
To explain it I am writing a selection query that creates an intermediate table that will be use in JOIN as second operand table.
Query is select all fist name and column those duplicates with some of other rows:
For example select rows in which
first
andlast
name repeatsSo you have only one pair of
first
andlast
names those repeats (or is duplicates with some other rows).Now, question is: how to select
id
of this row? Use Join! as follows:you can select on the basis of as many columns as you wants e.g. single column if you want using join then remove last name.