My head is spinning trying to figure out the SQL query I need to use. I have tried a variety of nested queries and self joins and everything is failing me. I assume I am WAY over thinking it.
Basic idea: I have a single table, let’s call it OrderTable and there are four (relevant) fields in the table: OrderId, CustomerId, RestaurantId, OrderTime
When a customer places an order, the date/time stamp is added to the OrderTime field. The other three fields are just integers, with the OrderId field as the primary key (and auto-increment).
I am trying to write a query that will return a list of CustomerId records where the first record (earliest date) for that customer is a specific date (let’s say ‘2012-03-14’) and the RestaurantId is a specific number (let’s say 29).
At the moment i have what i can only assume is an overly complicated way of doing it. Also, i currently get an error “#1242 – Subquery returns more than 1 row” when there is more than one record matching my subquery.
Can anyone help me with a more elegant solution? Thanks!
CURRENT QUERY:
SELECT `CustomerId`
FROM `OrderTable`
WHERE `OrderTime` LIKE '%2012-03-14%'
AND `RestaurantId`='29'
AND `OrderId`=(SELECT `OrderId`
FROM `OrderTable`
WHERE `RestaurantId`='29'
GROUP BY `CustomerId`
ORDER BY `OrderTime` ASC
)
EDIT: John Totet Woo was probably right on this one, but still refer to the second part of my post to avoid the LIKE clause 🙂
I might be slightly confused on what you’re asking for, but if you change the subquery from ‘=’ to IN, do you get what you’re after?
What was mostly bothering me though, is that you can use
Instead of the LIKE