SQL: select all customers that have all items expired - mysql

Consider the following DB structure
customer (id)
invoice (id, customer_id)
invoice_item (id, invoice_id, warranty_expiry)
I need to select all customers, where all their items are expired. Here is what I have so far
select * from customer c
inner join invoice i on c.id = i.customer_id
inner join invoice_item ii on i.id = ii.invoice_id
where ii.warranty_expiry < NOW()
group by c.id
having COUNT(ii.id) // <---
It feels like I should put something in HAVING clause, but I don't have an exact count of items for each client.

You can indeed use a having clause to ensure that the given customer has all their items expired. This works by moving the check on warranty_expiry from the where clause to the having clause, as follows:
select c.id
from customer c
inner join invoice i on c.id = i.customer_id
inner join invoice_item ii on i.id = ii.invoice_id
group by c.id
having max(ii.warranty_expiry >= NOW()) = 0
Note that select * and group by do not go along well (although older versions of MySQL do allow it by default). You should enumerate the columns that you want to retain in the select clause and in the group by clause.

You can simplify the query, because you don't need the customer table. Then I would go for:
select i.customer_id
from invoice i join
invoice_item ii
on i.id = ii.invoice_id
group by i.customer_id
having max(ii.waranty_expiry) < now();
This assumes that warnty_expiry is not null. If that is possible, then:
having max(ii.waranty_expiry) < now() and sum(ii.waranty_expiry is null) = 0;

Related

Left join issue using having clause with sum

I have two tables, products(id, name) and products_cost(id, sid, cost).
I'm trying to get a list of products whose total cost is less than 1000 including products that has no cost.
I've tried this:
SELECT a.name, SUM(b.cost) AS price
FROM products a
LEFT JOIN products_cost b
ON a.id = b.sid
GROUP BY a.name
HAVING SUM(b.cost)<1000;
The above SQL only gives the list of product name that includes cost and I want the output list to include product name that doesn't include cost as well.
I think you need to check for null values in the having clause:
SELECT p.name, SUM(pc.cost) AS price
FROM products p LEFT JOIN
products_cost pc
ON p.id = b.sid
GROUP BY p.name
HAVING SUM(pc.cost) < 1000 OR SUM(pc.cost) IS NULL;
Note that I also fixed the logic (salary doesn't makes sense in the SUM()). And I introduced meaningful table aliases -- abbreviations for the table names.
You can also add an IFNULL expression in your HAVING clause
SELECT a.name, SUM(b.cost) AS price
FROM products a
LEFT JOIN products_cost b
ON a.id = b.sid
GROUP BY a.name
HAVING SUM(IFNULL,b.cost,0)<1000;
use subquery and join
select p.*,a.s as cost from product p left join (
select pid,sum(cost) as s
from products_cost
group by pid
having s<1000 ) a on p.id=a.pid

MySQL Order By in Right Join Clause

I'm trying to do a right join in MySQL like so:
SELECT customers.id,customers.firstname,customers.lastname,customers.email,orders.time,orders.notes,pendings.date_updated,pendings.issue,appointments.closed,appointments.job_description,backup_plans.expiration FROM customers
RIGHT JOIN orders
ON customers.id = orders.customer_id
ORDER BY orders.time DESC LIMIT 1
RIGHT JOIN pendings
ON customers.id = pendings.customer_id
ORDER BY pendings.date_updated DESC LIMIT 1
RIGHT JOIN appointments
ON customers.id = appointments.customer_id
ORDER BY appointments.closed DESC LIMIT 1
RIGHT JOIN backup_plans
ON customers.id = backup_plans.customer_id
ORDER BY backup_plans.expiration DESC LIMIT 1
My intent is this: to select customers' name and email, along with the most recent order, pending, appointment, and backup plan exploration. When I execute this I get a syntax error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'RIGHT JOIN pendings
ON customers.id = pendings.customer_id
ORDER BY pendings.d' at line 5
I'm unfamiliar with joins and would appreciate any help.
EDIT 1:
It seems that I need to make a subquery per DanK's suggestion like so:
SELECT customers.id,customers.firstname,customers.lastname,customers.email,orderstmp.time,orderstmp.notes FROM customers
RIGHT JOIN (
SELECT orders.time,orders.notes,orders.customer_id FROM orders ORDER BY orders.time DESC LIMIT 1
) as orderstmp ON orderstmp.customer_id = customers.id
But when I do this, I only get one row result, whereas I want all the customer information.
EDIT 2:
Per Tom H's suggestion, I've built this query:
SELECT
customers.id,
SQ_O.time,
SQ_O.notes
FROM customers
LEFT JOIN (
SELECT
customers.id,
orders.time,
orders.notes
FROM customers
LEFT JOIN orders ON orders.customer_id = customers.id
ORDER BY orders.time DESC LIMIT 1
) AS SQ_O ON SQ_O.id = customers.id
which has all blank time and notes fields
and
SELECT
customers.id,
O1.time,
O1.notes
FROM customers
LEFT JOIN orders AS O1 ON O1.customer_id = O1.id
LEFT JOIN orders AS O2 ON O2.customer_id = customers.id AND O2.time > O1.time WHERE O2.customer_id IS NULL
Which reaches max execution time. I'm guessing this is due to my lack of familiarity with what's possible in MySQL in comparison to other dialects.
I also tried Correlated subqueries like this:
SELECT
customers.firstname,
customers.lastname,
customers.email,
(
SELECT CONCAT(orders.time,': ',orders.notes)
FROM orders
WHERE orders.customer_id = customers.id
ORDER BY orders.time DESC LIMIT 1
) as last_order
FROM customers
But the "last_order" column comes up blank.
FINAL, DISAPPOINTING EDIT
After trying a number of really stellar suggestions that helped me learn SQL significantly, I decided to write a PHP script to get me what I want. The project's under a bit of a deadline so whatever works, works. Thanks everyone!
You can only have one ORDER BY statement per query. You can of course use subqueries and refer to a result set as a virtual table but ultimately in a single SELECT you can only have one ORDER BY.
For instance:
SELECT something
FROM table
ORDER BY something -- One order By
With a subquery as a virtual table:
SELECT something
FROM (SELECT anotherthing, something
FROM table
ORDER BY anotherthing) -- this is an order by in a separate select statement..
ORDER BY something -- still only one Order by
------EDIT--------
For assistance with your join syntax, try something like this:
SELECT --fields,
FROM customers
RIGHT JOIN orders ON customers.id = orders.customer_id
RIGHT JOIN pendings ON customers.id = pendings.customer_id
RIGHT JOIN appointments ON customers.id = appointments.customer_id
RIGHT JOIN backup_plans ON customers.id = backup_plans.customer_id
ORDER BY orders.time DESC, pendings.date_updated DESC, appointments.closed DESC, backup_plans.expiration DESC
LIMIT 1
Try this:
SELECT customers.id,customers.firstname,customers.lastname,customers.email,orders.time,orders.notes,pendings.date_updated,pendings.issue,appointments.closed,appointments.job_description,backup_plans.expiration FROM customers
RIGHT JOIN orders
ON customers.id = orders.customer_id
RIGHT JOIN pendings
ON customers.id = pendings.customer_id
RIGHT JOIN appointments
ON customers.id = appointments.customer_id
RIGHT JOIN backup_plans
ON customers.id = backup_plans.customer_id
ORDER BY orders.time DESC, pendings.date_updated DESC, appointments.closed DESC, backup_plans.expiration DESC LIMIT 1
You can accomplish this through subqueries or with additional JOINs. Here's an example of each. (NOTE: I use SQL Server, so it's possible that some of the syntax that I'm used to isn't supported in the same way in MySQL). I'm only doing these example with the Orders, but hopefully you can extend the ideas to the other tables.
Using subqueries:
SELECT
C.id,
SQ_O.time,
SQ_O.notes
FROM
Customers C
LEFT OUTER JOIN
(
SELECT
C2.Customer_ID,
O.time,
O.notes
FROM
Customers C2
LEFT OUTER JOIN Orders O ON O.customer_id = C2.id
ORDER BY
O.time DESC LIMIT 1
) SQ_O ON SQ_O.customer_id = C.id
Using multiple JOINs:
SELECT
C.id,
O1.time,
O1.notes
FROM
Customers C
LEFT OUTER JOIN Orders O1 ON O1.customer_id = C.id
LEFT OUTER JOIN Orders O2 ON O2.customer_id = C.id AND O2.time > O1.time
WHERE
O2.customer_id IS NULL -- Basically we're excluding any rows where another order was found with a later time than O1
If exact matches in Orders.time are possible than you'll need additional criteria on which one to choose.
As long as you can rely on no customer having their two most recent orders having the same time, this should work:
SELECT c.firstname, c.lastname, c.email, o.*
FROM customers AS c
LEFT JOIN (
SELECT customer_id, MAX(`time`) AS maxTime
FROM orders
GROUP BY customer_id
) AS lastO ON c.id = lastO.customer_id
LEFT JOIN orders AS o
ON lastO.customer_id = o.customer_id
AND lastO.maxTime = o.`time`
;
As long as the other tables can also be relied upon to have only one MAX value per customer, you should be able to append similar JOINs for them. The issue with multiple of the same "last" time\date_updated\closed\etc.. for a customer is that they will multiply results. For example, pairs of the same time in orders and pairs of date_updated in pending on the same customer will result in 4 rows instead of two as every "last" row for that customer in orders is paired up with every "last" row in pending.

mySQL Sub Select needed

I have three tables, libraryitems, copies and loans.
A libraryitem hasMany copies, and a copy hasMany loans.
I'm trying to get the latest loan entry for a copy only; The query below returns all loans for a given copy.
SELECT
libraryitems.title,
copies.id,
copies.qruuid,
loans.id AS loanid,
loans.status,
loans.byname,
loans.byemail,
loans.createdAt
FROM copies
INNER JOIN libraryitems ON copies.libraryitemid = libraryitems.id AND libraryitems.deletedAt IS NULL
LEFT OUTER JOIN loans ON copies.id = loans.copyid
WHERE copies.libraryitemid = 1
ORDER BY copies.id ASC, loans.createdAt DESC
I know there needs to be a sub select of some description in here, but struggling to get the correct syntax. How do I only return the latest, i.e MAX(loans.createdAt) row for each distinct copy? Just using group by copies.id returns the earliest, rather than latest entry.
Image example below:
in the subquery , getting maximum created time for a loan i.e. latest entry and joining back with loans to get other details.
SELECT
T.title,
T.id,
T.qruuid,
loans.id AS loanid,
loans.status,
loans.byname,
loans.byemail,
loans.createdAt
FROM
(
SELECT C.id, C.qruuid, L.title, MAX(LN.createdAt) as maxCreatedTime
FROM Copies C
INNER JOIN libraryitems L ON C.libraryitemid = L.id
AND L.deletedAt IS NULL
LEFT OUTER JOIN loans LN ON C.id = LN.copyid
GROUP BY C.id, C.qruuid, L.title) T
JOIN loans ON T.id = loans.copyid
AND T.maxCreatedTime = loans.createdAt
A self left join on loans table will give you latest loan of a copy, you may join the query to the other tables to fetch the desired output.
select * from loans A
left outer join loans B
on A.copyid = B.copyid and A.createdAt < B.createdAt
where B.createdAt is null;
This is your query with one simple modification -- table aliases to make it clearer.
SELECT li.title, c.id, c.qruuid,
l.id AS loanid, l.status, l.byname, l.byemail, l.createdAt
FROM copies c INNER JOIN
libraryitems li
ON c.libraryitemid = li.id AND
li.deletedAt IS NULL LEFT JOIN
loans l
ON c.id = l.copyid
WHERE c.libraryitemid = 1
ORDER BY c.id ASC, l.createdAt DESC ;
With this as a beginning let's think about what you need. You want the load with the latest createdAt date for each c.id. You can get this information with a subquery:
select l.copyid, max(createdAt)
from loans
group by l.copyId
Now, you just need to join this information back in:
SELECT li.title, c.id, c.qruuid,
l.id AS loanid, l.status, l.byname, l.byemail, l.createdAt
FROM copies c INNER JOIN
libraryitems li
ON c.libraryitemid = li.id AND
li.deletedAt IS NULL LEFT JOIN
loans l
ON c.id = l.copyid LEFT JOIN
(SELECT l.copyid, max(l.createdAt) as maxca
FROM loans
GROUP BY l.copyid
) lmax
ON l.copyId = lmax.copyId and l.createdAt = lmax.maxca
WHERE c.libraryitemid = 1
ORDER BY c.id ASC, l.createdAt DESC ;
This should give you the most recent record. And, the use of left join should keep all copies, even those that have never been leant.

MySQL JOIN + Max

I need help writing a MySQL query. So far, none of the questions out there seem to fit my needs.
I have an order table and an order_log table. In the order_log table I make a record every time an order's status is changed. I need to display a list of the most recent status changes from the order_log table. The query I'm currently using does a JOIN on the two tables and grabs everything where order.status = order_log.status.
The problem with this is that some times an order will pass through the same status more than once. When that occurs, my query grabs every entry in the order_log table for that order and that status, but I only want the most recent log.
I tried writing a new JOIN query to grab the Max of the order_log date entry, but it's only returning 1 entry. This is what I have.
SELECT *
FROM order_status_log AS l
JOIN orders AS o ON ( l.order_id = o.id )
WHERE l.status = o.status
AND l.date = (
SELECT MAX( date )
FROM order_status_log l2
JOIN orders AS o2 ON ( l2.order_id = o2.id )
)
Any ideas?
there are many ways to do it, one is to have a separate subquery the gets the latest entry of each record: order_ID.
The result of the subquery is then joined back with the original table but has multiple conditions: that it matches the order_ID and also the latest date.
SELECT a.*, b.*
FROM `order` a
INNER JOIN order_log b
ON a.id = b.order_ID
INNER JOIN
(
SELECT order_ID, MAX(date) max_date
FROM order_log
GROUP BY order_ID
) c on b.order_ID = c.order_ID AND
b.date = c.max_date
That may help;
select olg.column1,o.column2,max(olg.date) from --You can add other columns as well
order_status_log olg
join orders o
on olg.id = o.order_id
group by olg.column1,o.column2

Update Query with Correlated Subquery

I'm trying to convert a Foxpro application into .NET. As part of that conversion I'm converting the data from DBF tables to Sql server.
I need to come up with a couple new fields in the Customer table based on the Orders table, FirstOrder and LastOrder.
I just can't seem to muddle through how to do this in TSql. I know how I'd do it in Foxpro, and I could actually still do it there if I had to, but I know I need to learn how to do this in Sql.
Here is the basic structure.
Customer Table has an Id, then the FirstOrder and LastOrder fields I need updated.
Order Table has OrderDate, but here is the real curve. The Customer Id can exist in 5 different fields inside the Order: ShipperId, PickupId, ConsigneeId, DeliveryId, or BillingId.
So something like:
UPDATE customers
SET FirstOrderDate =
(Select MIN(OrderDate)
FROM Orders o
WHERE o.ShipperId = Customers.Id or
o.PickupId = Customers.Id or
o.ConsigneeId = Customers.Id or
o.DeliveryId = Customers.Id or
o.BillingId = Customers.Id)
Just can't seem to find out how to tie the subquery with the main update query.
Thanks,
-Sid
EDIT:
Here's the SELECT that's working based on MarkD's suggestion:
Select C.Id,Min(o.OrderDate) as firstorder, MAX(o.OrderDate) as lastorder
from Customers C
JOIN Orders o
on o.ShipperId = C.Id or
o.PickupId = C.Id or
o.ConsigneeId = C.Id or
o.DeliveryId = C.Id or
o.BillingId = C.Id
GROUP BY C.Id
So now do I use this as a subquery or cursor to post back to the Customers table?
Although I think the JOIN criteria is highly unlikely, it looks like you're trying to do this?
EDIT: I've modified the JOIN criteria but this is what you're after.
Grouping By columns that are OR'd is odd.
;WITH MinOrderDates AS
(
SELECT CustID
,OrderDate = MIN(OrderDate)
FROM Orders
GROUP BY CustID
)
UPDATE C
SET FirstOrderDate = MIN(O.OrderDate)
FROM Customers C
JOIN MinOrderDates O ON C.Id = O.CustID
This is what your query would look like with the ORs
;WITH MinOrderDates AS
(
SELECT ShipperId
,PickupId
,ConsigneeId
,DeliveryId
.BillingId
,OrderDate = MIN(OrderDate)
FROM Orders
GROUP BY ShipperId
,PickupId
,ConsigneeId
,DeliveryId
.BillingId
)
UPDATE C
SET FirstOrderDate = MIN(O.OrderDate)
FROM Customers C
JOIN MinOrderDates O ON o.ShipperId = C.Id or
o.PickupId = C.Id or
o.ConsigneeId = C.Id or
o.DeliveryId = C.Id or
o.BillingId = C.Id
EDIT: Though I am having a hard time finding fault with your posted syntax.
Try this
UPDATE customers
SET FirstOrderDate =
(Select MIN(OrderDate)
FROM Orders
WHERE ShipperId = Customers.Id or
PickupId = Customers.Id or
ConsigneeId = Customers.Id or
DeliveryId = Customers.Id or
BillingId = Customers.Id)