Showing posts with label MySQL. Show all posts
Showing posts with label MySQL. Show all posts

Saturday, 10 September 2016

How to delete duplicate records from a table in MYSQL ?


Table Name : records
Procedure 1 :
Step 1 :
Create new table by removing duplicates
CREATE TABLE uniquerecords AS SELECT * FROM records GROUP BY name HAVING ( COUNT(name)>0 )
Step 2 :
Delete old table
DROP TABLE records
Step 3 :
Rename the New Table to Old Table
RENAME TABLE uniquerecords TO records
Procedure 2 : (IF Ajay is repeated five times, the below query would delete Ajay four times.)
QUERY :

DELETE FROM records USING records, records AS virtualtable WHERE (records.sno>virtualtable.sno) AND (records.name=virtualtable.name)
This would delete all the records except the first one.
Procedure 3 : (IF Ajay is repeated five times, the below query would delete all the five records.)
QUERY :

DELETE FROM records USING records, records AS virtualtable WHERE (records.sno=virtualtable.sno) AND (records.name=virtualtable.name)

How to get first 5 records from a table without using LIMIT in MYSQL ?


Table Name: records
Here, we have 10 records in the table, however, we need to retreive 5 records without using LIMIT keyword.
Query :
 SELECT limitrecordsone.sno,limitrecordsone.name FROM records limitrecordsone WHERE (SELECT COUNT(*) FROM records limitrecordstwo WHERE limitrecordstwo.sno <= limitrecordsone.sno) <=5
OUTPUT:

Get Player Name and Coach Name from a single table in MYSQL ?


Table Name: playercoach
Player Coach Table
Here, the number in the column coach represents the sno of the coach.
Procedure 1:
SELECT player.sno,player.name,(SELECT coach.name FROM playercoach coach WHERE coach.sno=player.coach) AS coachname FROM playercoach player
Procedure 2:
SELECT player.sno,player.name,coach.name AS coachname FROM playercoach player JOIN playercoach coach ON coach.sno=player.coach
Output:
Procedure 1 would be better in the sense of performance.