Você está na página 1de 6

INTRODUCTION TO MySQL: Selecting Data

Okay. We now have three related tables. We have a customers table, a pizzas table, and an orders table.

Wait a moment that means we have a database! Now we'll work on retrieving data from our database. And while we're at it, let's learn about some of the functions that we can use to work with said data. 1. Retrieving Data Using Select

You can retrieve data using the select command. This command requires two basic arguments what to select, and which table or tables to select it from. Lets look at a couple of quick examples. To retrieve all columns from all records in our customers table: mysql> select * from customers; To retrieve selected columns from all records in our customers table: mysql> select firstname, lastname from customers; To retrieve selected columns from selected rows in our customers table we include the where modifier: mysql> select firstname, lastname from customers where aarp="Y"; mysql> select firstname, lastname from customers where aarp="Y" and firstname="John"; MySQL Comparison Operands = <> or != < > <= >= equal to not equal to less than greater than less than or equals greater than or equals

If you want to select records based on part of a character value, you can use the like modifier: mysql> select firstname, lastname from customers where firstname like "Kev%"; In this example, we select only those records where the firstname begins with Kev. The percent sign is our truncation symbol. We would have returned the same records if we had searched for "kev%" the like statement is not case sensitive. And of course, we can combine our case selection criteria:

Introduction to MySQL: Session 2

mysql> select firstname, lastname from customers where firstname like "kev%" and aarp="Y"; This returns the first and last names of any customer whose name begins with kev and who is a member of the AARP. Suppose our pizzeria owner wanted to know what states she shipped pizzas to? How would she retrieve this data? OK, you are right that's too easy. This is the query: mysql> select state from customers; But wait; do you see a problem here? What do the results of this query look like? Need another hint? This provides the state for each record, even if that state has already been encountered. And this is not what our pizzeria owner wants. So, we can modify our select statement using the distinct attribute. This will only report a state the first time it is encountered. select distinct state from customers; That's better, isn't it? We now have 15 unique states. (Given the price of fuel, these must be very good pizzas!) But wait, there's more... What if we wanted to have our results in alphabetical order? Well, we can do that to by using the order by command: mysql> select distinct state from customers order by state; Wow, that is truly a thing of beauty. Looking at this data, our intrepid pizzeria owner wants to know the names of her customers in Maryland, Virginia, South Carolina and Tennessee. This should be easy, yes? We could do this: mysql> select firstname, lastname, city, state from customers where state like "VA" or state like "SC" or state like "TN" or state like "MD"; This could get really tedious to construct if the list of states was longer. We can shorten this syntax by using the in modifier: mysql> select firstname, lastname, city, state from customers where state in ("VA", "SC", "TN", "MD"); We can use this same structure to exclude records by using the not in modifier: mysql> select firstname, lastname, city, state from customers where state not in ("VA", "SC", "TN", "MD"); This returns everybody not in those four states. Phew! Okay, back to work... Our pizzeria owner now wants to know how many customers she has in each state. I know -- some folks are never satisfied! Anyhow, we can do this by grouping our data by state (using group by) and then counting the number of responses for each state. Like this:

Introduction to MySQL: Session 2

mysql> select state, count(*) from customers group by state order by state; Let's take a moment to review this SQL statement. First, we list the columns we want to include in our report these are state and count(*). Huh? What's this count(*) thing. We are looking at a function count() counts the number of rows that respond to the group command in this case, the number of rows(records) found for each state. The asterisk modifies the count statement to include all rows. After we declare the table upon which our query is to be executed, we issue our group by and order by modifiers. This is the result of our query: +-------+----------+ | state | count(*) | +-------+----------+ | AK | 2 | | AL | 1 | | AZ | 1 | | CA | 1 | | GA | 2 | | IL | 3 | | KY | 2 | | MA | 2 | | MD | 3 | | MO | 2 | | MS | 1 | | MT | 1 | | SC | 1 | | TN | 1 | | VA | 7 | +-------+----------+ 15 rows in set (0.00 sec)

Let's continue down this path. Its five years out and our pizza delivery service has grown exponentially. It's now so large that we have a marketing and sales department, and we want to split our customer base amongst our customer service representatives by their last name. Judy is to handle all customers whose last names begin with the letter a through the letter h. We can retrieve her data by modifying the where clause by using the between operator. mysql> select lastname, firstname, city, state from customers where lastname between 'a' and 'h';

2.

Joining Tables with the Inner Join

Relational databases succeed because the isolate information types into separate tables. In the project we've been working on, we have isolated data about customers in one table and orders in another. We could continue this model by creating a table for each delivery person, a table for inventory control and the like. The whole system depends upon the ability to connect, or join, tables together. And this depends on careful table design.

Introduction to MySQL: Session 2

Examine the structure of the customers and orders tables do you see a field that can link the two? Yup, its the customerid field. Any time the value in the customerid field in one table matches the customerid field in the other, we have a relationship, and we can work with data in both tables. There are two basic types of joins: the inner (equi) join, and the outer (left) join. Let's begin with the inner join. An inner join retrieves the desired columns from the specified tables whenever the linking field contains a common value. mysql> select customers.*, orders.* from customers, orders where customers.customerid=orders.customerid; In this example, we are selecting all columns from both tables whenever the customerid value in the customers table equals its counterpart in the orders table. Note that we are now specifying not only the name of the column but the table from which it is to be retrieved. This is required when there can be ambiguity between tables having identical column names, but it is good practice to always do this. An inner join only returns data when there is a positive match between specified tables. If we had a customer record in our customers table but that person had not yet ordered a pizza (thus no record in the orders table), we would not retrieve any data for this person. Let's add another record to our customers table but not to our orders table. mysql> insert into customers -> (lastname, firstname, addrline1, city, state, zip, areacode, phone, birthday, aarp) -> values -> ('Yott', 'Patrick', '264 Bowen Street', 'Providence', 'RI', '02906', '401', '338-3787', '1963-04-08', 'N'); Now lets do a couple of inner joins and see what happens: mysql> select customers.firstname, customers.lastname, orders.special from customers, orders where customers.customerid=orders.customerid and customers.lastname="yott"; mysql> select customers.firstname, customers.lastname, orders.special from customers, orders where customers.customerid=orders.customerid and customers.lastname="smith";

Notice that when we select only those records that have a common customerid value and a lastname value equal to "yott" that we don't get any results. But when we use smith as our last name we do. This is because there is no order record for yott in the customers table. 3. Aggregating Functions

Think back to when we counted the number of customers by state. That was an aggregating function. We used it to count all rows returned (designated by the asterisk). We can also count the number of rows containing data in a certain field like this:

Introduction to MySQL: Session 2

mysql> select count(*), count(addrline2) from customers; This returns the number of rows and the number of rows containing data in the second address column. This is pretty useful information. We can make the output more useful by adding labels to our columns using the as operator: mysql> select count(*) as "Total Records", count(addrline2) as "Completed 2nd Address Line" from customers; This command labels the count of total rows and the count of rows where addrline2 is not empty. Pretty neat! What if we wanted to add up a numeric column? What if we wanted to know how many total pizza's have been ordered? We could use the sum aggregator like this: mysql> select sum(quantity) from orders; And, we can assign a label to this as well: mysql> select customerid, sum(quantity) as "Total Pizza's Ordered" from orders; We can also determine the average number of pizza's ordered per order: mysql> select customerid, avg(quantity) as "Average Order" from orders; If we want to disaggregate by a column we can do this with the group by syntax: mysql> select customerid, sum(quantity) from orders group by customerid; Here is one final aggregated select. Here we want the average number of pizzas ordered for each customer ordering more than 4 pizzas. We have two aggregations going on a sum(quantity) and an avg(quantity). But we can't do a where selection on the aggregated variable instead, we use the having selection. mysql> select customerid, avg(quantity) from orders group by customerid having sum(quantity)>4;

4.

Inner Joins

The inner join works fine when there is a match between rows in the two (or more) tables being joined. But what if you wanted to retrieve data from both tables, even where there is not a match between all the rows? For example, what if there was a customer that had yet to order a pizza, but you wanted to see her contact information along with that of those customers that had ordered pizza. A typical inner join such as this:

Introduction to MySQL: Session 2

mysql> select firstname, lastname, pizzaid, orderdate from customers, orders where customers.customerid=orders.customerid; only returns data from rows where there is a match on the customerid field. Because of this, we only have data presented for those customers that have ordered at least one pizza. We can use a left, or outer, join to retrieve data for all customers regardless of whether they have ordered from our pizzeria or not. mysql> select firstname, lastname, pizzaid, orderdate from customers left join orders on customers.customerid=orders.customerid; The order in which you indicate your working tables is very important here. Your master table (the table from which you want all the records) must be to the left of the left join statement hence the name of the join.

Introduction to MySQL: Session 2

Você também pode gostar