views:

237

answers:

2

Let's say you have three tables named Item, Event, and Seat, constructed as such:

Item
Id (int)
Event_id (int)
Section (int)

Event
Id (int)
Venue_id (int)
Configuration (int)

Seat
Id (int)
Venue_id (int)
Configuration (int)
Section (int)
Face_value (int)

I'm trying to construct a MySQL query that pulls all entries from the Item table and includes the Face Value for each item. In order to do this, the query must:

  1. Use the Item.Event_id value and match it to Event.Id
  2. For that entry in the Event table, it must take the Event.Venue_id and Event.Configuration and find an entry in the Seat table that has the same values for both AND also has the same value for Section as Item.Section. It must then return Face_value.

I'm having a lot of trouble constructing this because of the way it combines info from all three tables. Any idea on how to approach it? Or is this impossible to do in SQL?

+3  A: 
SELECT `Item`.*, `Seat`.`Face_value`
FROM `Item`
JOIN `Event` ON `Event`.`Id` = `Item`.`Event_id`
JOIN `Seat` USING (`Venue_id`, `Configuration`)
WHERE `Seat`.`Section` = `Item`.`Section`
chaos
Thanks a ton. I'm trying to understand why this works--I'm assuming the order of the JOINs matters, right? Such that mysql knows that USING command is refers to identically-named variables in the Seat and Event tables?
Jack7890
It matters somewhat, yeah; the USING needs the identically-named columns to exists on either side of its JOIN. You could rewrite the query to join in a different order, though, and the USING is just for convenience, as Adam Bernier illustrates. I just wrote it the way that seemed intuitive to me.
chaos
+1  A: 

Same as chaos, but I prefer this syntax :-)

select s.Section, s.Configuration, s.Face_value
from   Item i
       inner join Event e
       on e.id = i.Event_id
       inner join Seat s
       on s.Venue_id = e.Venue_id
    and
        s.Configuration = e.Configuration
    and
        s.Section = i.Section
Adam Bernier
Thanks. The main difference between this and chaos' answer is that you use an INNER JOIN instead of a JOIN and you move the "s.Section = i.Section" part out of the WHERE clauses and into the ON clause, right? Will either of these changes hurt or improve performance?
Jack7890
INNER JOIN is the default when you write JOIN with no qualifier, so that's not actually a difference. We're both using inner joins. I don't *think* the WHERE vs. ON will affect performance, but it's not impossible that it could; I recommend running both to see. :) (And maybe EXPLAINing them too.)
chaos
Including it in the WHERE seems to run faster. Interesting.
Jack7890
Hunh. That's counterintuitive. But 'sall good; counterintuitive practical results are the reason to rely on profiling, not intuition. :)
chaos