I have 3 tables, users, sales and items. Right now I am doing 3 sql statements at once to get the data but was wondering how i do a statement so that it counts them all individually but in one statement.
So this:
SELECT count(*) AS total FROM sales WHERE status = 1
SELECT count(*) AS total FROM items WHERE status = 1
SELECT count(*) AS total FROM users WHERE status IN (1,2)
Merged all together to make one statement where the counters are assigned as total_sold, total_items and total_users.
How would i go about doing this? Thanks… Could i use union? (sql count statement) + (sql count statement)? I’m unsure. Thanks
SELECT 'total_sold' AS total_type
, COUNT(*) AS total
FROM sales
WHERE status = 1
UNION ALL
SELECT 'total_items'
, COUNT(*)
FROM items
WHERE status = 1
UNION ALL
SELECT 'total_users'
, COUNT(*)
FROM users
WHERE status IN (1,2)
SELECT (
SELECT COUNT(*)
FROM chewi1_m_sales
WHERE status = 1
) AS total_sales,
(
SELECT COUNT(*)
FROM chewi1_m_items
WHERE status = 1
) AS total_items,
(
SELECT COUNT(*)
FROM chewi1_users
WHERE status IN (1,2)
) AS total_users
If you take @r937’s SQL but don’t quote the strings, i.e.:
SELECT total_sold AS total_type -- Note: total_sold instead of 'total_sold'
, COUNT(*) AS total
FROM sales
WHERE status = 1
UNION ALL
SELECT total_items -- Note: total_items instead of 'total_items'
, COUNT(*)
FROM items
WHERE status = 1
UNION ALL
SELECT total_users -- Note: total_users instead of 'total_users'
, COUNT(*)
FROM users
WHERE status IN (1,2)
You would get exactly this error #1054 - Unknown column 'total_sold' in 'field list'
Which is also the error @jack55 got.