Welcome Guest, Not a member yet? Register   Sign In
Mysql -> getting results from two tables?
#14

[eluser]Johan André[/eluser]
Hey!

No problem! I like to help! Smile

Code:
SELECT
    *,
    (SELECT SUM(invoices.amount) FROM invoices WHERE invoices.due_date < NOW() AND invoices.user_id = users.id) AS total_amount_due,
    (SELECT SUM(invoices.amount) FROM invoices WHERE invoices.user_id = users.id) AS total_amount
FROM
    users
LEFT JOIN
    invoices ON users.id = invoices.user_id
GROUP BY
    users.id
ORDER BY
    users.username ASC

This code will list all your users. "total_amount_due" is the total of all invoices due. "total_amount" is the total of all invoices (including the ones that past the due-date). If a user does not have any invoices the "total_amount_due" and "total_amount" will be NULL.


Messages In This Thread
Mysql -> getting results from two tables? - by El Forum - 05-21-2009, 09:32 AM
Mysql -> getting results from two tables? - by El Forum - 05-21-2009, 09:42 AM
Mysql -> getting results from two tables? - by El Forum - 05-21-2009, 09:46 AM
Mysql -> getting results from two tables? - by El Forum - 05-21-2009, 09:54 AM
Mysql -> getting results from two tables? - by El Forum - 05-21-2009, 01:39 PM
Mysql -> getting results from two tables? - by El Forum - 05-22-2009, 02:35 AM
Mysql -> getting results from two tables? - by El Forum - 05-22-2009, 02:53 AM
Mysql -> getting results from two tables? - by El Forum - 05-22-2009, 04:46 AM
Mysql -> getting results from two tables? - by El Forum - 05-22-2009, 04:55 AM
Mysql -> getting results from two tables? - by El Forum - 05-22-2009, 05:36 AM
Mysql -> getting results from two tables? - by El Forum - 05-22-2009, 06:01 AM
Mysql -> getting results from two tables? - by El Forum - 05-22-2009, 06:16 AM
Mysql -> getting results from two tables? - by El Forum - 05-22-2009, 06:57 AM
Mysql -> getting results from two tables? - by El Forum - 05-22-2009, 08:19 AM
Mysql -> getting results from two tables? - by El Forum - 05-22-2009, 10:55 AM
Mysql -> getting results from two tables? - by El Forum - 05-22-2009, 03:19 PM
Mysql -> getting results from two tables? - by El Forum - 08-20-2009, 06:53 AM



Theme © iAndrew 2016 - Forum software by © MyBB