I have 3 tables in a MySQL database.
Table 1 (say it’s called client) has information of a client: client_id and client_name
Table 2 (say it’s called user_to_client) has information related to each client with the users of my system: user_id, client_id and order_flag.
In this table clients and users are repeated, order flag indicates that the user and client have unfinished business. A combination of user_id and client_id can only be found once in that table, it means user 5 and client 3 is only registered one time.
Table 3 (called orders) keeps information about the basic information of an order: client_id, user_id, order_id. It keeps two different date type columns: date_started which keeps information of the date when they started to build the order and date_sent which keeps the date when the order was sent to the operations area.
The reason I repeat the information in two tables is because in table 3, user and client can have a ton of unfinished orders which are no longer available, but i need to keep for the company records.
So, what i need to do is select the 4 last clients with unfinished orders without repeating the clients, and the id to that last unfinished order. Basically i need to select from table 1 the client name, if that client has in table 2 order_flag activated (value 1) and from table 3 the latest order_id which belongs to that user.
I cannot modify the tables because they are being used for another job already, so, can someone help me with a MySQL query to accomplish the job?
The following query does not query answer your question, because clients can be repeated. However, it provides a good basis for figuring out what to do:
I’m not sure how you find “unfinished” orders. So, I’m guessing that it is based on date_sent being NULL.
What you actually need is a bit more complicated. You want the most recent “unfinished” order for each client. The following query uses a correlated subquery to get this information:
This makes the assumption that it can find the right order based on the client id and date. If this is not true, then the correlated subquery has to bring in the other tables to get the right filtering information.