table: users
columns: id
table: products
columns: id
table: product_images
columns: product_id | path
table: cart
columns: user_id | product_id
product_id in the bottom 2 tables corresponds to id in the products table. user_id in the cart table corresponds to id in the users table.
My friend and I are developing a generic shopping website just for fun.
The requirement: Given a user_id, go through the user's shopping cart and return all corresponding rows in the products table and with exactly 1 image for the product (there may be multiple images).
This is our query (which seems to work):
SELECT products.*, product_images.path
FROM products
INNER JOIN cart
ON cart.product_id = products.id AND cart.user_id = 13 /* arbitrary id */
LEFT OUTER JOIN product_images
ON product_images.product_id = cart.product_id
GROUP BY cart.product_id
The first join is intuitive to me because both tables involved in the join are joining on columns within each table.
It is the 2nd join that I am confused about.
My understanding is that the first join will produce a virtual table.
This virtual table is then joined with the product_images table, but the confusing part is that the ON condition is not using a column belonging directly to the virtual table.
So what exactly is going on here?
Please note that I know how to rewrite the query in a way that is more intuitive to me, and that it is understanding the concept that is important to me.
At first I thought this was uncommon, but I noticed w3schools does the same thing at the bottom of this link: http://www.w3schools.com/sql/sql_groupby.asp