SQL Subselects

Let’s say you’ve got three tables, Cars, Makes, Models. What if you need to get a list of cars including their Make and Model?

Here’s where subselects come in.

The Tables:

Cars
—————
id
MakeID
ModelID
Colour
ImageLink

Makes
———
id
Name

Models
———-
id
MakeID
Model

And here’s the query:

select c.id,
(select name from makes where id = c.makeid) as make,
m.model as model
from cars c
inner join models as m on c.modelid = m.id

 

Advertisements
Posted in SQL

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: