Self join : Simple JOIN « Join « SQL / MySQL






Self join

  
/*
mysql> SELECT p1.name, p1.sex, p2.name, p2.sex, p1.species
    ->        FROM bird AS p1, bird AS p2
    ->        WHERE p1.species = p2.species AND p1.sex = 'f' AND p2.sex = 'm';
+-----------+------+----------+------+---------+
| name      | sex  | name     | sex  | species |
+-----------+------+----------+------+---------+
| BlueBird1 | f    | RedBird1 | m    | Bus     |
| BlueBird1 | f    | RedBird3 | m    | Bus     |
| BlueBird1 | f    | RedBird4 | m    | Bus     |
+-----------+------+----------+------+---------+
3 rows in set (0.04 sec)


*/
Drop table Bird;

CREATE TABLE Bird (
    name VARCHAR(20), 
    owner VARCHAR(20),
    species VARCHAR(20), 
    sex CHAR(1), 
    birth DATE, 
    death DATE
);
     
INSERT INTO  Bird VALUES ('BlueBird1','Joe','Bus','f','1999-03-30',NULL);
INSERT INTO  Bird VALUES ('RedBird1','Yin','Bus','m','1979-04-30',1998-01-30);
INSERT INTO  Bird VALUES ('BlueBird2','Joe','Car','f','1999-03-30',NULL);
INSERT INTO  Bird VALUES ('RedBird3','Yin','Bus','m','1979-04-30',1998-01-30);
INSERT INTO  Bird VALUES ('RedBird4','Yin','Bus','m','1998-01-30',NULL);
       
  
SELECT p1.name, p1.sex, p2.name, p2.sex, p1.species
       FROM bird AS p1, bird AS p2
       WHERE p1.species = p2.species AND p1.sex = 'f' AND p2.sex = 'm';

           
         
    
  








Related examples in the same category

1.Using More Than one Table
2.Simple table join
3.Join three tables
4.Query data from two tables
5.JOIN two tables with alias name
6.Using a Join to Control Query Output Order
7.Using a Join to Create a Lookup Table from Descriptive Labels
8.Return the first names and surnames of both the sales rep and the customer, as well as the value of the sale
9.Query data from two tables 2
10.Finding Rows in One Table That Match Rows in Another
11.Identify records from author table that corresponds to the author name, use its a_id value to find matching re
12.Using information in the book table to find information in the author table
13.Finding Rows with No Match in Another Table
14.Shorten the output column list to include only columns from the author table
15.List each author from the author table, and whether or not you have any books by the author
16.Using table alias to qualify column name when column names exist
17.Using table alias to qualify column name
18.PSEUDONYMS FOR TABLE NAMES
19.Qualify the column name with table name