combining 2 or more sql statements
-
hey there! ive got four queries that need combining 1:
SELECT amount, notes FROM credit WHERE customer_Id = $cust_id
2:
SELECT amount, notes FROM payment WHERE customer_Id = $cust_id
3:
SELECT sum( amount ) AS totalpaid FROM payment WHERE customer_Id = $cust_id
4:
SELECT sum( amount ) AS totaltaken FROM credit WHERE customer_Id = $cust_id
im not totally fluent at sql queries but these are the queries that id like to be able to retreive all at once via ine single query instead of the repetition four times, any help appreciated thanks abu ;P
-
hey there! ive got four queries that need combining 1:
SELECT amount, notes FROM credit WHERE customer_Id = $cust_id
2:
SELECT amount, notes FROM payment WHERE customer_Id = $cust_id
3:
SELECT sum( amount ) AS totalpaid FROM payment WHERE customer_Id = $cust_id
4:
SELECT sum( amount ) AS totaltaken FROM credit WHERE customer_Id = $cust_id
im not totally fluent at sql queries but these are the queries that id like to be able to retreive all at once via ine single query instead of the repetition four times, any help appreciated thanks abu ;P
Try this:
SELECT amount, notes FROM credit WHERE customer_Id = $cust_id
UNION ALL
SELECT amount, notes FROM payment WHERE customer_Id = $cust_id
UNION ALL
SELECT sum( amount ), '' AS totalpaid FROM payment WHERE customer_Id = $cust_id
UNION ALL
SELECT sum( amount ), '' AS totaltaken FROM credit WHERE customer_Id = $cust_id -
hey there! ive got four queries that need combining 1:
SELECT amount, notes FROM credit WHERE customer_Id = $cust_id
2:
SELECT amount, notes FROM payment WHERE customer_Id = $cust_id
3:
SELECT sum( amount ) AS totalpaid FROM payment WHERE customer_Id = $cust_id
4:
SELECT sum( amount ) AS totaltaken FROM credit WHERE customer_Id = $cust_id
im not totally fluent at sql queries but these are the queries that id like to be able to retreive all at once via ine single query instead of the repetition four times, any help appreciated thanks abu ;P
-
Try this:
SELECT amount, notes FROM credit WHERE customer_Id = $cust_id
UNION ALL
SELECT amount, notes FROM payment WHERE customer_Id = $cust_id
UNION ALL
SELECT sum( amount ), '' AS totalpaid FROM payment WHERE customer_Id = $cust_id
UNION ALL
SELECT sum( amount ), '' AS totaltaken FROM credit WHERE customer_Id = $cust_id -
when you do this,it only union those fields,can not make sum(amount) show as an Independent field.how could we do?
SELECT SUM(A.amount) FROM (
SELECT amount, notes FROM credit WHERE customer_Id = $cust_id
UNION ALL
SELECT amount, notes FROM payment WHERE customer_Id = $cust_id
UNION ALL
SELECT sum( amount ), '' AS totalpaid FROM payment WHERE customer_Id = $cust_id
UNION ALL
SELECT sum( amount ), '' AS totaltaken FROM credit WHERE customer_Id = $cust_id
) A;
Regards, Arun Kumar.A