Consider following schema:
Customers: Col | Type | -------------------| id | INTEGER | name | VARCHAR | Orders: Col | Type | ----------------------| id | INTEGER | customer_id | INTEGER | date | DATE | Items Col | Type | ----------------------| id | INTEGER | order_id | INTEGER | name | VARCHAR | quantity | INTEGER |
And here's the breif run down of the schema: Customer can have many orders, and an order can have many items Note: You may argue that the items should refer to some products table with a product_id, but let it be simple as is now.
From my database, I want to ask following question:
For a given customer, list all the items that start with La.
My version of the query goes like this:
SELECT * FROM items WHERE name LIKE 'La%'
This would return ALL the items that Begin with La for ALL the customers. What I want is that I get all the items for a SPECIFIC customer with say id 1. How do I write such a query? My second version that would do is like this:
SELECT * FROM items WHERE name LIKE 'La%' AND order_id in (SELECT id FROM orders WHERE customer_id=1);
But is their any other efficient/elegant or a more better way to do the same thing?