11.07.2015 Views

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

www.it-ebooks.infoCHAPTER 35 • PRACTICAL DATABASE QUERIESA subquery enables you to combine these tasks into a single query in order to determine whichmembers share a ZIP code with member Jason Gilmore, like so:SELECT id, first_name, last_name FROM membersWHERE zip = (SELECT zip FROM members WHERE id=1);This returns the following output:+----+------------+------------+| id | first_name | last_name |+----+------------+--------- --+| 1 | Jason | Gilmore || 3 | Sean | Blum || 4 | Jodi | Stiles |+----+------------+------------+Performing Comparisons with SubqueriesSubqueries are also very useful for performing comparisons. For example, suppose that you added acolumn titled daily_mileage to the members table, and prompted members to add this information totheir profile for research purposes. You are interested to know which members travel more than theaverage of all members on the site. The following query makes this determination:SELECT first_name, last_name FROM members WHEREdaily_mileage > (SELECT AVG(daily_mileage) FROM members);You’re free to use any of <strong>MySQL</strong>’s supported comparison operators and aggregation functions whencreating subqueries.Determining Existence with SubqueriesBuilding on the carpool theme, suppose that your web site prompts members to list the types of vehiclesat their disposal (a motorcycle, van, or four-door car, for instance). Because some members couldpossess multiple vehicles, two new tables are created to map this relation. The first table, vehicles,stores a list of vehicle types and descriptions:CREATE TABLE vehicles (id INT UNSIGNED NOT NULL AUTO_INCREMENT,name VARCHAR(25) NOT NULL,description VARCHAR(100),PRIMARY KEY(id));The second table, member_to_vehicle, maps member IDs to vehicle IDs:CREATE TABLE member_to_vehicle (member_id INT UNSIGNED NOT NULL,vehicle_id INT UNSIGNED NOT NULL,PRIMARY KEY(member_id, vehicle_id));685

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!