- Use nicknames,or aliases, in queies to save typing and allow a table to be used more than once in a query.
- Aggregate data into groups so you can discover sums,averages,and counts.
- Join Tables in different ways.
- Use nested queries
- Save query results in variables so they can be reused in other queries.
1.Aliases
Column Aliases
mysql>
mysql> SELECT first_name as 'First Name',last_name as 'Last Name'
-> FROM actor LIMIT 5;
ERROR 1146 (42S02): Table 'sakila_new.actor' doesn't exist
mysql> show database;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'database' at line 1
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| employees |
| lu |
| lu;cy |
| lucy |
| mysql |
| performance_schema |
| sakila |
| sakila_new |
| sys |
| world |
+--------------------+
11 rows in set (0.00 sec)
mysql> use sakila
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql>
mysql> SELECT first_name as 'First Name',last_name as 'Last Name'
-> FROM actor LIMIT 5;
+------------+--------------+
| First Name | Last Name |
+------------+--------------+
| PENELOPE | CRUZ |
| NICK | WAHLBERG |
| ED | CHASE |
| JENNIFER | DAVIS |
| JOHNNY | LOLLOBRIGIDA |
+------------+--------------+
5 rows in set (0.00 sec)
mysql> SELECT CONCAT(first_name, ' ', last_name, ' played in ', title) AS movie
-> FROM actor JOIN film_actor USING (actor_id)
-> JOIN film USING (film_id)
-> ORDER BY movie LIMIT 20;
+--------------------------------------------+
| movie |
+--------------------------------------------+
| ADAM GRANT played in ANNIE IDENTITY |
| ADAM GRANT played in BALLROOM MOCKINGBIRD |
| ADAM GRANT played in DISCIPLE MOTHER |
| ADAM GRANT played in FIREBALL PHILADELPHIA |
| ADAM GRANT played in GLADIATOR WESTWARD |
| ADAM GRANT played in GLORY TRACY |
| ADAM GRANT played in GROUNDHOG UNCUT |
| ADAM GRANT played in HAPPINESS UNITED |
| ADAM GRANT played in IDOLS SNATCHERS |
| ADAM GRANT played in LOSER HUSTLER |
| ADAM GRANT played in MARS ROMAN |
| ADAM GRANT played in MIDNIGHT WESTWARD |
| ADAM GRANT played in OPERATION OPERATION |
| ADAM GRANT played in SEABISCUIT PUNK |
| ADAM GRANT played in SPLENDOR PATTON |
| ADAM GRANT played in TADPOLE PARK |
| ADAM GRANT played in TWISTED PIRATES |
| ADAM GRANT played in WANDA CHAMBER |
| ADAM HOPPER played in BLINDNESS GUN |
| ADAM HOPPER played in BLOOD ARGONAUTS |
+--------------------------------------------+
20 rows in set (0.02 sec)
mysql> SELECT CONCAT(first_name, ' ', last_name, ' played in ', title) AS movie FROM actor JOIN film_actor USING (actor_id) JOIN film USING (film_id) ORDER BY CONCAT(first_name, ' ',last_name, ' played in
', title) LIMIT 20;
+--------------------------------------------+
| movie |
+--------------------------------------------+
| ADAM GRANT played in ANNIE IDENTITY |
| ADAM GRANT played in BALLROOM MOCKINGBIRD |
| ADAM GRANT played in DISCIPLE MOTHER |
| ADAM GRANT played in FIREBALL PHILADELPHIA |
| ADAM GRANT played in GLADIATOR WESTWARD |
| ADAM GRANT played in GLORY TRACY |
| ADAM GRANT played in GROUNDHOG UNCUT |
| ADAM GRANT played in HAPPINESS UNITED |
| ADAM GRANT played in IDOLS SNATCHERS |
| ADAM GRANT played in LOSER HUSTLER |
| ADAM GRANT played in MARS ROMAN |
| ADAM GRANT played in MIDNIGHT WESTWARD |
| ADAM GRANT played in OPERATION OPERATION |
| ADAM GRANT played in SEABISCUIT PUNK |
| ADAM GRANT played in SPLENDOR PATTON |
| ADAM GRANT played in TADPOLE PARK |
| ADAM GRANT played in TWISTED PIRATES |
| ADAM GRANT played in WANDA CHAMBER |
| ADAM HOPPER played in BLINDNESS GUN |
| ADAM HOPPER played in BLOOD ARGONAUTS |
+--------------------------------------------+
20 rows in set (0.03 sec)
mysql> select first_name as name from actor where name = 'ZERO CAGE';
ERROR 1054 (42S22): Unknown column 'name' in 'where clause'
mysql> select actor_id as id FROM actor WHERE first_name = 'ZERO';
+----+
| id |
+----+
| 11 |
+----+
1 row in set (0.00 sec)
mysql> SELECT actor_id id from actor where first_name = 'ZERO';
+----+
| id |
+----+
| 11 |
+----+
1 row in set (0.00 sec)
mysql>
Tables Aliases
mysql>
mysql> SELECT ac.actor_id,ac.first_name,ac.last_name,fl.title from actor as ac inner join film_actor as fla using (actor_id) inner join film as fl using (film_id) where fl.title = 'AFFAIR PREJUDICE';
+----------+------------+-----------+------------------+
| actor_id | first_name | last_name | title |
+----------+------------+-----------+------------------+
| 41 | JODIE | DEGENERES | AFFAIR PREJUDICE |
| 81 | SCARLETT | DAMON | AFFAIR PREJUDICE |
| 88 | KENNETH | PESCI | AFFAIR PREJUDICE |
| 147 | FAY | WINSLET | AFFAIR PREJUDICE |
| 162 | OPRAH | KILMER | AFFAIR PREJUDICE |
+----------+------------+-----------+------------------+
5 rows in set (0.00 sec)
mysql> SELECT ac.actor_id,ac.first_name,ac.last_name,fl.title from actor as ac inner join film_actor as fla using (actor_id) inner join film as fl using (film_id) where film.title = 'AFFAIR PREJUDICE';
ERROR 1054 (42S22): Unknown column 'film.title' in 'where clause'
mysql>
mysql> select * from film where title = title limit 5;
+---------+------------------+-----------------------------------------------------------------------------------------------------------------------+--------------+-------------+----------------------+-----------------+-------------+--------+------------------+--------+----------------------------------+---------------------+
| film_id | title | description | release_year | language_id | original_language_id | rental_duration | rental_rate | length | replacement_cost | rating | special_features | last_update |
+---------+------------------+-----------------------------------------------------------------------------------------------------------------------+--------------+-------------+----------------------+-----------------+-------------+--------+------------------+--------+----------------------------------+---------------------+
| 1 | ACADEMY DINOSAUR | A Epic Drama of a Feminist And a Mad Scientist who must Battle a Teacher in The Canadian Rockies | 2006 | 1 | NULL | 6 | 0.99 | 86 | 20.99 | PG | Deleted Scenes,Behind the Scenes | 2006-02-15 05:03:42 |
| 2 | ACE GOLDFINGER | A Astounding Epistle of a Database Administrator And a Explorer who must Find a Car in Ancient China | 2006 | 1 | NULL | 3 | 4.99 | 48 | 12.99 | G | Trailers,Deleted Scenes | 2006-02-15 05:03:42 |
| 3 | ADAPTATION HOLES | A Astounding Reflection of a Lumberjack And a Car who must Sink a Lumberjack in A Baloon Factory | 2006 | 1 | NULL | 7 | 2.99 | 50 | 18.99 | NC-17 | Trailers,Deleted Scenes | 2006-02-15 05:03:42 |
| 4 | AFFAIR PREJUDICE | A Fanciful Documentary of a Frisbee And a Lumberjack who must Chase a Monkey in A Shark Tank | 2006 | 1 | NULL | 5 | 2.99 | 117 | 26.99 | G | Commentaries,Behind the Scenes | 2006-02-15 05:03:42 |
| 5 | AFRICAN EGG | A Fast-Paced Documentary of a Pastry Chef And a Dentist who must Pursue a Forensic Psychologist in The Gulf of Mexico | 2006 | 1 | NULL | 6 | 2.99 | 130 | 22.99 | G | Deleted Scenes | 2006-02-15 05:03:42 |
+---------+------------------+-----------------------------------------------------------------------------------------------------------------------+--------------+-------------+----------------------+-----------------+-------------+--------+------------------+--------+----------------------------------+---------------------+
5 rows in set (0.00 sec)
mysql>
mysql> select m1.film_id,m2.title from film as m1,film as m2 where m1.title = m2.title limit 5;
+---------+------------------+
| film_id | title |
+---------+------------------+
| 1 | ACADEMY DINOSAUR |
| 2 | ACE GOLDFINGER |
| 3 | ADAPTATION HOLES |
| 4 | AFFAIR PREJUDICE |
| 5 | AFRICAN EGG |
+---------+------------------+
5 rows in set (0.00 sec)
mysql> select m1.film_id,m2.title from film as m1,film as m2 where m1.title = m2.title and m1.film_id <> m2.film_id limit 5;
Empty set (0.00 sec)
mysql>
2.Aggregating Data
The DISTINCT Clause
mysql> select first_name
-> from actor join film_actor using (actor_id)
-> limit 5;
+------------+
| first_name |
+------------+
| PENELOPE |
| PENELOPE |
| PENELOPE |
| PENELOPE |
| PENELOPE |
+------------+
5 rows in set (0.00 sec)
mysql> select distinct first_name,last_name
-> from actor join film_actor using(actor_id);
+-------------+--------------+
| first_name | last_name |
+-------------+--------------+
| PENELOPE | CRUZ |
| NICK | WAHLBERG |
| ED | CHASE |
| JENNIFER | DAVIS |
| JOHNNY | LOLLOBRIGIDA |
| BETTE | NICHOLSON |
| GRACE | MOSTEL |
| MATTHEW | JOHANSSON |
| JOE | SWANK |
| CHRISTIAN | GABLE |
| ZERO | CAGE |
| KARL | BERRY |
| UMA | WOOD |
| VIVIEN | BERGEN |
| CUBA | OLIVIER |
| FRED | COSTNER |
| HELEN | VOIGHT |
| DAN | TORN |
| BOB | FAWCETT |
| LUCILLE | TRACY |
| KIRSTEN | PALTROW |
| ELVIS | MARX |
| SANDRA | KILMER |
| CAMERON | STREEP |
| KEVIN | BLOOM |
| RIP | CRAWFORD |
| JULIA | MCQUEEN |
| WOODY | HOFFMAN |
| ALEC | WAYNE |
| SANDRA | PECK |
| SISSY | SOBIESKI |
| TIM | HACKMAN |
| MILLA | PECK |
| AUDREY | OLIVIER |
| JUDY | DEAN |
| BURT | DUKAKIS |
| VAL | BOLGER |
| TOM | MCKELLEN |
| GOLDIE | BRODY |
| JOHNNY | CAGE |
| JODIE | DEGENERES |
| TOM | MIRANDA |
| KIRK | JOVOVICH |
| NICK | STALLONE |
| REESE | KILMER |
| PARKER | GOLDBERG |
| JULIA | BARRYMORE |
| FRANCES | DAY-LEWIS |
| ANNE | CRONYN |
| NATALIE | HOPKINS |
| GARY | PHOENIX |
| CARMEN | HUNT |
| MENA | TEMPLE |
| PENELOPE | PINKETT |
| FAY | KILMER |
| DAN | HARRIS |
| JUDE | CRUISE |
| CHRISTIAN | AKROYD |
| DUSTIN | TAUTOU |
| HENRY | BERRY |
| CHRISTIAN | NEESON |
| JAYNE | NEESON |
| CAMERON | WRAY |
| RAY | JOHANSSON |
| ANGELA | HUDSON |
| MARY | TANDY |
| JESSICA | BAILEY |
| RIP | WINSLET |
| KENNETH | PALTROW |
| MICHELLE | MCCONAUGHEY |
| ADAM | GRANT |
| SEAN | WILLIAMS |
| GARY | PENN |
| MILLA | KEITEL |
| BURT | POSEY |
| ANGELINA | ASTAIRE |
| CARY | MCCONAUGHEY |
| GROUCHO | SINATRA |
| MAE | HOFFMAN |
| RALPH | CRUZ |
| SCARLETT | DAMON |
| WOODY | JOLIE |
| BEN | WILLIS |
| JAMES | PITT |
| MINNIE | ZELLWEGER |
| GREG | CHAPLIN |
| SPENCER | PECK |
| KENNETH | PESCI |
| CHARLIZE | DENCH |
| SEAN | GUINESS |
| CHRISTOPHER | BERRY |
| KIRSTEN | AKROYD |
| ELLEN | PRESLEY |
| KENNETH | TORN |
| DARYL | WAHLBERG |
| GENE | WILLIS |
| MEG | HAWKE |
| CHRIS | BRIDGES |
| JIM | MOSTEL |
| SPENCER | DEPP |
| SUSAN | DAVIS |
| WALTER | TORN |
| MATTHEW | LEIGH |
| PENELOPE | CRONYN |
| SIDNEY | CROWE |
| GROUCHO | DUNST |
| GINA | DEGENERES |
| WARREN | NOLTE |
| SYLVESTER | DERN |
| CAMERON | ZELLWEGER |
| RUSSELL | BACALL |
| MORGAN | HOPKINS |
| MORGAN | MCDORMAND |
| HARRISON | BALE |
| DAN | STREEP |
| RENEE | TRACY |
| CUBA | ALLEN |
| WARREN | JACKMAN |
| PENELOPE | MONROE |
| LIZA | BERGMAN |
| SALMA | NOLTE |
| JULIANNE | DENCH |
| SCARLETT | BENING |
| ALBERT | NOLTE |
| FRANCES | TOMEI |
| KEVIN | GARLAND |
| CATE | MCQUEEN |
| DARYL | CRAWFORD |
| GRETA | KEITEL |
| JANE | JACKMAN |
| ADAM | HOPPER |
| RICHARD | PENN |
| GENE | HOPKINS |
| RITA | REYNOLDS |
| ED | MANSFIELD |
| MORGAN | WILLIAMS |
| LUCILLE | DEE |
| EWAN | GOODING |
| WHOOPI | HURT |
| CATE | HARRIS |
| JADA | RYDER |
| RIVER | DEAN |
| ANGELA | WITHERSPOON |
| KIM | ALLEN |
| ALBERT | JOHANSSON |
| FAY | WINSLET |
| EMILY | DEE |
| RUSSELL | TEMPLE |
| JAYNE | NOLTE |
| GEOFFREY | HESTON |
| BEN | HARRIS |
| MINNIE | KILMER |
| MERYL | GIBSON |
| IAN | TANDY |
| FAY | WOOD |
| GRETA | MALDEN |
| VIVIEN | BASINGER |
| LAURA | BRODY |
| CHRIS | DEPP |
| HARVEY | HOPE |
| OPRAH | KILMER |
| CHRISTOPHER | WEST |
| HUMPHREY | WILLIS |
| AL | GARLAND |
| NICK | DEGENERES |
| LAURENCE | BULLOCK |
| WILL | WILSON |
| KENNETH | HOFFMAN |
| MENA | HOPPER |
| OLYMPIA | PFEIFFER |
| GROUCHO | WILLIAMS |
| ALAN | DREYFUSS |
| MICHAEL | BENING |
| WILLIAM | HACKMAN |
| JON | CHASE |
| GENE | MCKELLEN |
| LISA | MONROE |
| ED | GUINESS |
| JEFF | SILVERSTONE |
| MATTHEW | CARREY |
| DEBBIE | AKROYD |
| RUSSELL | CLOSE |
| HUMPHREY | GARLAND |
| MICHAEL | BOLGER |
| JULIA | ZELLWEGER |
| RENEE | BALL |
| ROCK | DUKAKIS |
| CUBA | BIRCH |
| AUDREY | BAILEY |
| GREGORY | GOODING |
| JOHN | SUVARI |
| BURT | TEMPLE |
| MERYL | ALLEN |
| JAYNE | SILVERSTONE |
| BELA | WALKEN |
| REESE | WEST |
| MARY | KEITEL |
| JULIA | FAWCETT |
| THORA | TEMPLE |
+-------------+--------------+
199 rows in set (0.00 sec)
mysql>
The GROUP BY Clause
mysql> select first_name from actor
-> where first_name in ('GENE','MERYL');
+------------+
| first_name |
+------------+
| GENE |
| GENE |
| MERYL |
| GENE |
| MERYL |
+------------+
5 rows in set (0.00 sec)
mysql>
mysql> SELECT first_name from actor
-> where first_name in ('GENE','MERYL')
-> group by first_name;
+------------+
| first_name |
+------------+
| GENE |
| MERYL |
+------------+
2 rows in set (0.00 sec)
mysql> select first_name,last_name,film_id
-> from actor inner join film_actor using (actor_id)
-> order by first_name,last_name limit 20;
+------------+-----------+---------+
| first_name | last_name | film_id |
+------------+-----------+---------+
| ADAM | GRANT | 26 |
| ADAM | GRANT | 52 |
| ADAM | GRANT | 233 |
| ADAM | GRANT | 317 |
| ADAM | GRANT | 359 |
| ADAM | GRANT | 362 |
| ADAM | GRANT | 385 |
| ADAM | GRANT | 399 |
| ADAM | GRANT | 450 |
| ADAM | GRANT | 532 |
| ADAM | GRANT | 560 |
| ADAM | GRANT | 574 |
| ADAM | GRANT | 638 |
| ADAM | GRANT | 773 |
| ADAM | GRANT | 833 |
| ADAM | GRANT | 874 |
| ADAM | GRANT | 918 |
| ADAM | GRANT | 956 |
| ADAM | HOPPER | 81 |
| ADAM | HOPPER | 82 |
+------------+-----------+---------+
20 rows in set (0.00 sec)
mysql> select first_name,last_name,count(film_id) as num_films from
-> actor inner join film_actor using (actor_id)
-> group by first_name,last_name
-> order by num_films desc limit 5;
+------------+-----------+-----------+
| first_name | last_name | num_films |
+------------+-----------+-----------+
| SUSAN | DAVIS | 54 |
| GINA | DEGENERES | 42 |
| WALTER | TORN | 41 |
| MARY | KEITEL | 40 |
| MATTHEW | CARREY | 39 |
+------------+-----------+-----------+
5 rows in set (0.00 sec)
mysql>
Aggregate functions
count()
avg()
max()
min()
STD(),STDDEV(),STDDEV_POP()
SUM()
The Having Clause
mysql> select first_name,last_name,count(film_id)
-> from actor inner join film_actor using (actor_id)
-> group by actor_id,first_name,last_name
-> having count(film_id) > 40
-> order by count(film_id) desc;
+------------+-----------+----------------+
| first_name | last_name | count(film_id) |
+------------+-----------+----------------+
| GINA | DEGENERES | 42 |
| WALTER | TORN | 41 |
+------------+-----------+----------------+
2 rows in set (0.01 sec)
mysql>
mysql>
mysql> select title,count(rental_id) as num_rented FROM
-> film inner join inventory using (film_id)
-> inner join rental using (inventory_id)
-> group by title
-> having num_rented > 30
-> order by num_rented desc limit 5;
+---------------------+------------+
| title | num_rented |
+---------------------+------------+
| BUCKET BROTHERHOOD | 34 |
| ROCKETEER MOTHER | 33 |
| JUGGLER HARDLY | 32 |
| RIDGEMONT SUBMARINE | 32 |
| FORWARD TEMPLE | 32 |
+---------------------+------------+
5 rows in set (0.02 sec)
mysql> select first_name,last_name,count(film_id) as film_cnt from actor inner join film_actor using (actor_id) group by actor_id,first_name,last_name having first_name = 'EMILY' AND
last_name = 'DEE';
+------------+-----------+----------+
| first_name | last_name | film_cnt |
+------------+-----------+----------+
| EMILY | DEE | 14 |
+------------+-----------+----------+
1 row in set (0.01 sec)
mysql> select first_name,last_name,count(film_id) as film_cnt from
-> actor inner join film_actor using (actor_id)
-> where first_name = 'EMILY' and last_name = 'DEE'
-> group by actor_id,first_name,last_name;
+------------+-----------+----------+
| first_name | last_name | film_cnt |
+------------+-----------+----------+
| EMILY | DEE | 14 |
+------------+-----------+----------+
1 row in set (0.00 sec)
mysql>
Advanced Joins
The inner join
The keyphrase INNER JOIN can be replaced with JOIN or STRAIGHT JOIN ;They all do the same thing.
mysql> select first_name,last_name,film_id from actor inner join film_actor using(actor_id) limit 20;
+------------+-----------+---------+
| first_name | last_name | film_id |
+------------+-----------+---------+
| PENELOPE | GUINESS | 1 |
| PENELOPE | GUINESS | 23 |
| PENELOPE | GUINESS | 25 |
| PENELOPE | GUINESS | 106 |
| PENELOPE | GUINESS | 140 |
| PENELOPE | GUINESS | 166 |
| PENELOPE | GUINESS | 277 |
| PENELOPE | GUINESS | 361 |
| PENELOPE | GUINESS | 438 |
| PENELOPE | GUINESS | 499 |
| PENELOPE | GUINESS | 506 |
| PENELOPE | GUINESS | 509 |
| PENELOPE | GUINESS | 605 |
| PENELOPE | GUINESS | 635 |
| PENELOPE | GUINESS | 749 |
| PENELOPE | GUINESS | 832 |
| PENELOPE | GUINESS | 939 |
| PENELOPE | GUINESS | 970 |
| PENELOPE | GUINESS | 980 |
| NICK | WAHLBERG | 3 |
+------------+-----------+---------+
20 rows in set (0.00 sec)
mysql> select first_name,last_name,film_id
-> from actor,film_actor
-> where actor.actor_id = film_actor.actor_id
-> limit 20;
+------------+-----------+---------+
| first_name | last_name | film_id |
+------------+-----------+---------+
| PENELOPE | GUINESS | 1 |
| PENELOPE | GUINESS | 23 |
| PENELOPE | GUINESS | 25 |
| PENELOPE | GUINESS | 106 |
| PENELOPE | GUINESS | 140 |
| PENELOPE | GUINESS | 166 |
| PENELOPE | GUINESS | 277 |
| PENELOPE | GUINESS | 361 |
| PENELOPE | GUINESS | 438 |
| PENELOPE | GUINESS | 499 |
| PENELOPE | GUINESS | 506 |
| PENELOPE | GUINESS | 509 |
| PENELOPE | GUINESS | 605 |
| PENELOPE | GUINESS | 635 |
| PENELOPE | GUINESS | 749 |
| PENELOPE | GUINESS | 832 |
| PENELOPE | GUINESS | 939 |
| PENELOPE | GUINESS | 970 |
| PENELOPE | GUINESS | 980 |
| NICK | WAHLBERG | 3 |
+------------+-----------+---------+
20 rows in set (0.00 sec)
mysql> select first_name,last_name,film_id from
-> actor inner join film_actor
-> on actor.actor_id = film_actor.actor_id
-> limit 20;
+------------+-----------+---------+
| first_name | last_name | film_id |
+------------+-----------+---------+
| PENELOPE | GUINESS | 1 |
| PENELOPE | GUINESS | 23 |
| PENELOPE | GUINESS | 25 |
| PENELOPE | GUINESS | 106 |
| PENELOPE | GUINESS | 140 |
| PENELOPE | GUINESS | 166 |
| PENELOPE | GUINESS | 277 |
| PENELOPE | GUINESS | 361 |
| PENELOPE | GUINESS | 438 |
| PENELOPE | GUINESS | 499 |
| PENELOPE | GUINESS | 506 |
| PENELOPE | GUINESS | 509 |
| PENELOPE | GUINESS | 605 |
| PENELOPE | GUINESS | 635 |
| PENELOPE | GUINESS | 749 |
| PENELOPE | GUINESS | 832 |
| PENELOPE | GUINESS | 939 |
| PENELOPE | GUINESS | 970 |
| PENELOPE | GUINESS | 980 |
| NICK | WAHLBERG | 3 |
+------------+-----------+---------+
20 rows in set (0.00 sec)
mysql>
The Union
The UNION operator has several limitations:
- The output is labeled with the names of the columns or expressions from the first query.
- The queries must output the same number of columns.If you try using different numbers of columns ,MySQL will report an error.
- All matching columns must have the same type .
- The result returned are unique,as if you'd applied a distinct to the overall result set.
The Left and Right Joins
The Natural Join
mysql> # The Natural Join
mysql> select first_name,last_name,film_id
-> from actor_info natural join film_actor
-> limit 20;
+------------+-----------+---------+
| first_name | last_name | film_id |
+------------+-----------+---------+
| PENELOPE | GUINESS | 1 |
| PENELOPE | GUINESS | 23 |
| PENELOPE | GUINESS | 25 |
| PENELOPE | GUINESS | 106 |
| PENELOPE | GUINESS | 140 |
| PENELOPE | GUINESS | 166 |
| PENELOPE | GUINESS | 277 |
| PENELOPE | GUINESS | 361 |
| PENELOPE | GUINESS | 438 |
| PENELOPE | GUINESS | 499 |
| PENELOPE | GUINESS | 506 |
| PENELOPE | GUINESS | 509 |
| PENELOPE | GUINESS | 605 |
| PENELOPE | GUINESS | 635 |
| PENELOPE | GUINESS | 749 |
| PENELOPE | GUINESS | 832 |
| PENELOPE | GUINESS | 939 |
| PENELOPE | GUINESS | 970 |
| PENELOPE | GUINESS | 980 |
| NICK | WAHLBERG | 3 |
+------------+-----------+---------+
20 rows in set (0.50 sec)
mysql> select first_name,last_name,film_id from
-> actor_info join film_actor
-> where (actor_info.actor_id = film_actor.actor_id)
-> limit 20;
+------------+-----------+---------+
| first_name | last_name | film_id |
+------------+-----------+---------+
| PENELOPE | GUINESS | 1 |
| PENELOPE | GUINESS | 23 |
| PENELOPE | GUINESS | 25 |
| PENELOPE | GUINESS | 106 |
| PENELOPE | GUINESS | 140 |
| PENELOPE | GUINESS | 166 |
| PENELOPE | GUINESS | 277 |
| PENELOPE | GUINESS | 361 |
| PENELOPE | GUINESS | 438 |
| PENELOPE | GUINESS | 499 |
| PENELOPE | GUINESS | 506 |
| PENELOPE | GUINESS | 509 |
| PENELOPE | GUINESS | 605 |
| PENELOPE | GUINESS | 635 |
| PENELOPE | GUINESS | 749 |
| PENELOPE | GUINESS | 832 |
| PENELOPE | GUINESS | 939 |
| PENELOPE | GUINESS | 970 |
| PENELOPE | GUINESS | 980 |
| NICK | WAHLBERG | 3 |
+------------+-----------+---------+
20 rows in set (0.49 sec)
mysql>
Constant Expressions in Joins
Nested Queries
Nested Query Basics
The ANY,SOME,ALL,IN ,and NOT IN Clauses
Using ANY and IN
mysql> SELECT emp_no, first_name, last_name, hire_date
-> FROM employees JOIN titles USING (emp_no)
-> WHERE title = 'Assistant Engineer'
-> AND hire_date < ANY (SELECT hire_date FROM
-> employees JOIN titles USING (emp_no)
-> WHERE title = 'Manager');
mysql> select hire_date from
-> employees join titles using (emp_no)
-> where title = 'Manager';
mysql> select emp_no,first_name,last_name
-> from employees join titles using (emp_no)
-> where title = 'Manager'
-> and emp_no = ANY(select emp_no from employees join titles using (emp_no) where title <> 'Manager');
Using ALL
We can use the alias NOT IN in place of <> ANY or != ANY.
Writing row subqueries
mysql> select mgr.emp_no,YEAR(mgr.from_date) as fd
-> from titles as mgr,titles as other
-> where mgr.emp_no = other.emp_no
-> and mgr.title = 'Manager'
-> and mgr.title <> other.title
-> and year(mgr.from_date) = Year(other.from_date);
+--------+------+
| emp_no | fd |
+--------+------+
| 110765 | 1989 |
| 111784 | 1988 |
+--------+------+
2 rows in set (0.15 sec)
mysql> select emp_no,Year(from_date) as fd
-> from titles where title = 'Manager' and
-> (emp_no,year(from_date)) IN
-> (select emp_no,year(from_date)
-> from titles where title <> 'Manager');
+--------+------+
| emp_no | fd |
+--------+------+
| 110765 | 1989 |
| 111784 | 1988 |
+--------+------+
2 rows in set (0.15 sec)
The EXISTS and NOT EXISTS Clauses
EXISTS and NOT EXISTS basics
mysql> select first_name,last_name from staff
-> where exists (select * from customer
-> where customer.first_name = staff.first_name
-> and customer.last_name = staff.last_name);
Empty set (0.00 sec)
mysql> INSERT INTO customer(store_id,first_name,last_name,email,address_id,create_date) values(1,'Mike','Hillyer','Mike.Hillyer@sakilastaff.com',3,now());
Query OK, 1 row affected (0.01 sec)
mysql> select first_name,last_name from staff
-> where exists (select * from customer
-> where customer.first_name = staff.first_name
-> and customer.last_name = staff.last_name);
+------------+-----------+
| first_name | last_name |
+------------+-----------+
| Mike | Hillyer |
+------------+-----------+
1 row in set (0.00 sec)
mysql> select count(*) from film where exists
-> (select film_id from inventory
-> where inventory.film_id = film.film_id
-> group by film_id having count(*) >= 2);
+----------+
| count(*) |
+----------+
| 958 |
+----------+
1 row in set (0.01 sec)
mysql>
Use the In and finds managers who also had some other position:
mysql> select emp_no,first_name,last_name from employees join titles using (emp_no) where title = 'Manager' and emp_no IN (select emp_no from employees join titles using (emp_no) where title <> 'Manager');
rewritten query:
mysql> select emp_no,first_name,last_name
-> from employees join titles using (emp_no)
-> where title = 'Manager'
-> and exists (select emp_no from titles
-> where titles.emp_no = employees.emp_no
-> and title <> 'Manager');
Nested Queries in the FROM Clause
mysql> select emp_no,monthly_salary from
-> (select emp_no,salary/12 as monthly_salary from salaries) as ms limit 5;
+--------+----------------+
| emp_no | monthly_salary |
+--------+----------------+
| 10001 | 5009.7500 |
| 10001 | 5175.1667 |
| 10001 | 5506.1667 |
| 10001 | 5549.6667 |
| 10001 | 5580.0833 |
+--------+----------------+
5 rows in set (0.00 sec)
mysql> # derived table must have an alias,even if we don''t use the alias in our query.
mysql>
mysql> select emp_no,monthly_salary from
-> (select emp_no,salary/12 as monthly_salary from salaries) limit 5;
ERROR 1248 (42000): Every derived table must have its own alias
mysql>
User Variables
The following query finds the title of a film and saves the result in a user variable:
mysql> SELECT @film:=title from film where film_id = 1;
+------------------+
| @film:=title |
+------------------+
| ACADEMY DINOSAUR |
+------------------+
1 row in set (0.00 sec)
mysql> select @film;
+------------------+
| @film |
+------------------+
| ACADEMY DINOSAUR |
+------------------+
1 row in set (0.00 sec)
mysql> select @film:=title from film where film_id = 1;
+------------------+
| @film:=title |
+------------------+
| ACADEMY DINOSAUR |
+------------------+
1 row in set (0.00 sec)
mysql> show warnings\G
Empty set (0.02 sec)
mysql> set @film := (select title from film where film_id = 1);
Query OK, 0 rows affected (0.01 sec)
mysql> select @film;
+------------------+
| @film |
+------------------+
| ACADEMY DINOSAUR |
+------------------+
1 row in set (0.00 sec)
mysql>
Second,we can use the SELECT INTO statement:
mysql> select title into @film from film where film_id = 1;
Query OK, 1 row affected (0.00 sec)
mysql> select @film;
+------------------+
| @film |
+------------------+
| ACADEMY DINOSAUR |
+------------------+
1 row in set (0.00 sec)
mysql>
You can explicity set a variable using the set statement without a select.Suppose you want to initialize a counter to zero.
mysql> set @counter := 0;
Query OK, 0 rows affected (0.00 sec)
mysql> set @counter = 0,@age := 23;
Query OK, 0 rows affected (0.00 sec)
mysql> select 0 into @counter;
Query OK, 1 row affected (0.00 sec)
mysql> select 0, 23 into @counter,@age;
Query OK, 1 row affected (0.00 sec)
mysql> select max(rental_date) from rental
-> join customer using (customer_id)
-> where email = 'WESLEY.BULL@sakilacustomer.org';
+---------------------+
| max(rental_date) |
+---------------------+
| 2005-08-23 15:46:33 |
+---------------------+
1 row in set (0.00 sec)
mysql> select title from film
-> join inventory using (film_id)
-> join rental using (inventory_id)
-> join customer using (customer_id)
-> where email = 'WESLEY.BULL@sakilacustomer.org'
-> and rental_date = '2005-08-23 15:46:33';
+-------------+
| title |
+-------------+
| KARATE MOON |
+-------------+
1 row in set (0.01 sec)
mysql> select max(rental_date) into @recent from rental
-> join customer using (customer_id)
-> where email = 'WESLEY.BULL@sakilacustomer.org';
Query OK, 1 row affected (0.00 sec)
mysql> select title from film
-> join inventory using (film_id)
-> join rental using (inventory_id)
-> join customer using (customer_id)
-> where email = 'WESLEY.BULL@sakilacustomer.org'
-> and rental_date = @recent;
+-------------+
| title |
+-------------+
| KARATE MOON |
+-------------+
1 row in set (0.00 sec)
mysql>