Add the result of SELECT query in another SELECT query - mysql

This is the result of a UNION of two SELECT
SELECT count(*) FROM
((SELECT session_id_current_user from test.tws_analytics
WHERE (add_date BETWEEN '2022-05-15' AND '2022-05-15') AND ((pathURL='vues/login.php' AND name_current_user='') OR (pathURL='' AND searchURL='?job=forgotten' AND name_current_user=''))
AND session_id_current_user NOT IN
(SELECT session_id_current_user from test.tws_analytics
WHERE (pathURL <> 'vues/login.php' AND searchURL <> '?job=forgotten') AND add_date BETWEEN '2022-05-15' AND '2022-05-15' order by session_id_current_user)
order by session_id_current_user)
UNION
(SELECT name_current_user from test.tws_analytics where add_date BETWEEN '2022-05-15' AND '2022-05-15' AND name_current_user IS NOT NULL AND name_current_user <> ''))
AS tem
The result is 11.
What I want to do is to select this result with other columns like this :
SELECT count(session),count(name), [AND tem.count(*)] FROM ....
This is the general idea, though i didn't know how to implement it.

a simplified general answer would be
select * from (select count(*) numsessions from sessions), (select count(*) numusers from users)
this will give 2 different counts, i didn't include the logics that you provided, but that will need to be done inside the 2 subqueries.

Related

order by with union in SQL is not working

Is it possible to order when the data comes from many select and union it together? Such as
In this statement, the vouchers data is not showing in the same sequence as I saved on the database, I also tried it with "ORDER BY v_payments.payment_id ASC" but won't be worked
( SELECT order_id as id, order_date as date, ... , time FROM orders WHERE client_code = '$searchId' AND order_status = 1 AND order_date BETWEEN '$start_date' AND '$end_date' ORDER BY time)
UNION
( SELECT vouchers.voucher_id as id, vouchers.payment_date as date, v_payments.account_name as name, ac_balance as oldBalance, v_payments.debit as debitAmount, v_payments.description as descriptions,
vouchers.v_no as v_no, vouchers.v_type as v_type, v_payments.credit as creditAmount, time, zero as tax, zero as freightAmount FROM vouchers INNER JOIN v_payments
ON vouchers.voucher_id = v_payments.voucher_id WHERE v_payments.client_code = '$searchId' AND voucher_status = 1 AND vouchers.payment_date BETWEEN '$start_date' AND '$end_date' ORDER BY v_payments.payment_id ASC , time )
UNION
( SELECT return_id as id, return_date as date, ... , time FROM w_return WHERE client_code = '$searchId' AND w_return_status = 1 AND return_date BETWEEN '$start_date' AND '$end_date' ORDER BY time)
Wrap the sub-select queries in the union within a SELECT
SELECT id, name
FROM
(
SELECT id, name FROM fruits
UNION
SELECT id, name FROM vegetables
)
foods
ORDER BY name
If you want the order to only apply to one of the sub-selects, use parentheses as you are doing.
Note that depending on your DB, the syntax may differ here. And if that's the case, you may get better help by specifying what DB server (MySQL, SQL Server, etc.) you are using and any error messages that result.
You need to put the ORDER BY at the end of the statement i.e. you are ordering the final resultset after union-ing the 3 intermediate resultsets
To use an ORDER BY or LIMIT clause to sort or limit the entire UNION result, parenthesize the individual SELECT statements and place the ORDER BY or LIMIT after the last one. See link below:
ORDER BY and LIMIT in Unions
(SELECT a FROM t1 WHERE a=10 AND B=1)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2)
ORDER BY a LIMIT 10;

SQL merge different table data counts

Below is my query to get some data for dashboard screen.
SELECT COUNT(*) as occupied_rooms FROM rooms where available='N' ;
SELECT COUNT(*) as checkedIn_guests FROM booking where checkout_time='' ;
SELECT COUNT(*) as available_rooms FROM rooms where available='Y' ;
SELECT COUNT(*) as total_guest FROM booking;
SELECT COUNT(*) as total_booking FROM booking;
SELECT COUNT(*) as total_staff FROM employee;
It produce output as show in above
How ever I want the output like given above image.
Use union all
SELECT 'occupied_rooms' as which, COUNT(*) as cnt FROM rooms where available = 'N'
UNION ALL
SELECT 'checkedIn_guests', COUNT(*) FROM booking where checkout_time = ''
UNION ALL
SELECT 'available_rooms', COUNT(*) FROM rooms where available = 'Y' ;
UNION ALL
SELECT 'total_guest', COUNT(*) FROM booking;
UNION ALL
SELECT 'total_booking', COUNT(*) FROM booking;
UNION ALL
SELECT 'total_staff', COUNT(*) FROM employee;
You could make the query a bit more efficient by combining the queries that reference the same table. But the overall structure would be essentially the same.
You could use a UNION for build single table result with each result in a row
SELECT 'occupied_rooms', COUNT(*) count
FROM rooms
where available='N'
UNION
SELECT 'checkedIn_guests', COUNT(*)
FROM booking
where checkout_time=''
UNION
SELECT 'available_rooms', COUNT(*)
FROM rooms
where available='Y'
UNION
SELECT 'total_guest', COUNT(*)
FROM booking
UNION
SELECT 'total_booking', COUNT(*)
FROM booking
UNION
SELECT 'total_staff', COUNT(*)
FROM employee;

Select Count with Distinct and Union All

I have a query like :
SELECT COUNT(DISTINCT `ID`) FROM db1.table UNION ALL SELECT COUNT(DISTINCT `ID`) FROM db2.table
My real query is more complicate, i have LEFT JOIN and multiple condition etc...
This query return to me an array with 2 results : Count 1 and Count 2
How can i only return one result ? Count 1 + Count 2 ?
Thanks !
Try this:
SELECT (SELECT COUNT(DISTINCT `ID`) FROM db1.table) +
(SELECT COUNT(DISTINCT `ID`) FROM db2.table)
If you also want to return separate db1, db2 counts, then use this query:
SELECT countDb1, countDb2, countDb1 + countDb2 AS total
FROM (
SELECT (SELECT COUNT(DISTINCT `ID`) FROM db1.table) AS countDb1,
(SELECT COUNT(DISTINCT `ID`) FROM db2.table) AS countDb2) AS t

MySQL; Get information from 3 table same time

People
here is my little problem.
I have three table:
a_names_1
b_names_2
c_names_3
they are same by structure. all of them has two item: name and used
Is there any QUERY to run to get and count all the 'name' that has 'used'=1 from all those three tables together.
I've tried this one, but didn't work:
(SELECT COUNT(*) 'name' from a_names_1) UNION
(SELECT COUNT(*) 'name' from a_names_2) UNION
(SELECT COUNT(*) 'name' from a_names_3) WHERE `used`=1
I'm using PHPMyAdmin for MySQL.
Any Help would be appreciated.. thanks in advance
This query outputs count of distinct names from all tables with used=1
select count(distinct name)
from
(
select name,used from a_names_1 where used=1
union all
select name,used from a_names_2 where used=1
union all
select name,used from a_names_3 where used=1
) t
If you need to SUM all USED for each NAME from all tables and output only with SUM of used=1 then:
select count(*) from
(
select name, SUM(used)
from
(
select name,used from a_names_1
union all
select name,used from a_names_2
union all
select name,used from a_names_3
) t
GROUP BY name
HAVING SUM(used)=1
) t1
select count(*) as name
from
(
select name, used from a_names_1
union
select name, used from a_names_2
union
select name, used from a_names_3) t
where t.used = 1
Probably this is slow, because you lose the index optimizations. What I would do is do the three queries, something like
SELECT SUM('name') AS name_sum
FROM ((SELECT COUNT(*) 'name' from a_names_1 WHERE `used`=1)
UNION (SELECT COUNT(*) 'name' from a_names_2 WHERE `used`=1));
If this doesn't work, it is probably a problem with the usage of name
Maybe you wanted this way:
select count(*) as cnt
from
(
select name from a_names_1 t1 where t1.used = 1
union
select name from a_names_2 t2 where t2.used = 1
union
select name from a_names_3 t3 where t3.used = 1
) t
The straight forward solution;
SELECT SUM(used) FROM (
SELECT used FROM a_names_1 WHERE used=1
UNION ALL
SELECT used FROM a_names_2 WHERE used=1
UNION ALL
SELECT used FROM a_names_3 WHERE used=1
) a
SQLfiddle for testing
An alternative if you have an index on used (and the only values of used are 0 or 1) is to just do the counting using the index;
SELECT SUM(used) total FROM (
SELECT SUM(used) used FROM a_names_1
UNION ALL
SELECT SUM(used) FROM a_names_2
UNION ALL
SELECT SUM(used) FROM a_names_3
) a
SQLfiddle for this example.
If you look at the query plan of the latter query, you can see it uses the indexes effectively.

How to calculate Sum of Count(*) in Mysql

I have two tables that I count rows of them. For example;
Select count(*) FROM tbl_Events
Select count(*) FROM tbl_Events2
I need total count. How can I sum the result with a single statement?
select sum(cnt) from (
select count(*) as cnt from tbl_events
union all
select count(*) as cnt from tbl_events2
) as x
Try this:
SELECT (Select count(*) FROM tbl_Events) + (Select count(*) FROM tbl_Events2)
Or (tested in MSSQL), this:
SELECT COUNT(*)
FROM (SELECT * FROM tbl_Events
UNION ALL
SELECT * FROM tbl_Events2) AS AllEvents
I'd guess the first will lead to better performance because it has more obvious index options. Test to be sure, though.
Select Count(*)
From(
Select * From tbl_Events
Union All
Select * From tbl_Events2) as A