Count mysql union type query - php

I have a union type query. How can I count the number of rows it queries?
mysql_query(
" (SELECT 1 as sort_col,performerid,pic0
FROM $table
WHERE performerid IS NOT NULL $performeridSql)
UNION
(SELECT 2 as sort_col,performerid,pic0
FROM $table
WHERE performerid IS NOT NULL
$categorySql $buildSql
$breastsize $haircolor $age $ethnicity
$willingnessSql)
ORDER BY sort_col");

Simply count the subquery results...
SELECT COUNT(t.*) FROM
( (SELECT 1 AS sort_col,performerid,pic0
FROM $table
WHERE performerid IS NOT NULL
$performeridSql)
UNION
(SELECT 2 AS sort_col,performerid,pic0
FROM $table
WHERE performerid IS NOT NULL
$categorySql $buildSql
$breastsize $haircolor $age $ethnicity
$willingnessSql)
ORDER BY sort_col)
) AS t

If you need the results in addition to the count, the likes of mysqli_result::num_rows or PDOStatement::rowCount will return what you want. Otherwise, run your query as a subquery, then apply the COUNT aggregate function to the result.

Related

How to add non-empty values from two tables in mySQL DB using php?

I have two tables inside a mysql database. table_1 and table_2
Both of these tables have 4 columns for users
user_1, user_2, user_3 and user_4
Now using PHP I first want to fetch the non-null values from two tables and I use this query.
<?php
$query1 = "
select * from table_1 where user_1!='' and user_1 is not null
union all
select * from table_1 where user_2!='' and user_2 is not null
union all
select * from table_1 where user_3!='' and user_3 is not null
union all
select * from table_1 where user_4!='' and user_4 is not null
";
Then I fetch it and count the entries total = mysqli_num_rows and it gives me correct details as 3.
Similarly I do it for table_2
<?php
$query2 = "
select * from table_2 where user_1!='' and user_1 is not null
union all
select * from table_2 where user_2!='' and user_2 is not null
union all
select * from table_2 where user_3!='' and user_3 is not null
union all
select * from table_2 where user_4!='' and user_4 is not null
";
and it shows me total count as 2 which is correct.
But when I add count1 and count2
$count1 = mysqli_num_rows($data1);
$count2 = mysqli_num_rows($data2);
$total = $count1+$count2;
It shows either 1 or some weird value.Please suggest a fix
Everything depends on what $data1 and $data2 is. If they contain the results of $query and $query2, respectively, then one could expect the result to be 5. However, since your result is different, it follows that $data1 and $data2 is not what you think. So, in order to find out what the problem is, you will need to find out what $data1 and $data2 is. You will need to var_dump them and analyze what their value is, detect the nature of the anomaly. Once that's done, you will need to look at the code and figure out how that value was ending up into your variables.
to getting which column is not empty, you should add some condition as AND and if your fields have whitespace please consider TRIM condition such as:
SELECT * FROM `table_1` WHERE `user_1` IS NOT NULL AND TRIM(column) <> '' union all
notice: if you want use more than one command in php variable as string, you should add semicolon on end of each command
$query ="
SELECT * FROM `table_1` WHERE `user_1` IS NOT NULL AND TRIM(user_1) <> '' union all;
SELECT * FROM `table_2` WHERE `user_2` IS NOT NULL AND TRIM(user_2) <> '' union all;
SELECT * FROM `table_3` WHERE `user_3` IS NOT NULL AND TRIM(user_3) <> '' union all;
"

How to find the distinct values with total number of rows?

I want result in a single query.
Currently, I am using 2 queries. First for the distinct rows and the second is for the count rows. Second query fire for each row of the first query. Which is not good for the server.
I tried it in a single query but it shows count as 1 for each row which is wrong. I don't know how to do it in a single query.
Please help!
2 queries:
SELECT DISTINCT `_car_make`.`id` as `make_id`, `_car_make`.`title`
FROM `_motor`, `_car_make`
WHERE `_motor`.`make` = `_car_make`.`id`
AND `domain` = 'domain.com' AND `active` = 'y' AND `_motor`.`status` != 'SOLD'
GROUP BY `_motor`.`id` ORDER BY `_car_make`.`title`
SELECT COUNT(DISTINCT `id`) AS `TOTAL_MAKE` FROM `_motor`
WHERE `_motor`.`make` = '$make_id'
AND `domain` = 'domain.com' AND `_motor`.`status` != 'SOLD' AND `active` = 'y'
I tried it in 1 query, which shows count as 1 which is wrong:
SELECT DISTINCT `_car_make`.`id` as `make_id`, `_car_make`.`title`, count(`_motor`.`id`) AS TotalMake
FROM `_motor`, `_car_make`
WHERE `_motor`.`make` = `_car_make`.`id`
AND `domain` = 'domain.com' AND `active` = 'y' AND `_motor`.`status` != 'SOLD'
GROUP BY `_motor`.`id` ORDER BY `_car_make`.`title`
You can try below-
SELECT `_car_make`.`id` as `make_id`, `_car_make`.`title`, count(*) AS TotalMake
FROM `_motor` inner join `_car_make`
on `_motor`.`make` = `_car_make`.`id`
AND `domain` = 'coxheathcarcentre.co.uk'
where `active` = 'y' AND `_motor`.`status` != 'SOLD'
GROUP BY `_car_make`.`id`,`_car_make`.`title`
ORDER BY `_car_make`.`title`

Sum value of all rows of a column with multiple tables

Im using this to get a total count
$exe = mysql_query('SELECT SUM(field_3) FROM t_a');
$res = mysql_fetch_row($exe);
echo 'Total Count: ' .$res[0] . ' / XX';
But I need it from multiple tables with the same structure, named t_a, t_b, all the way to t_z
You can use Union All in my sql
select sum(field_3) total
from
(
select field_3
from t_a
union all
select field_3
from t_b
) t
group by field_3

count aggregate in query select on laravel4

I have the select like this:
StoreProduct::where('user_id', Auth::user()->main_id)
->whereNotExists(function($query)
{
$query->select(DB::raw(1))
->from('store_products')
->whereRaw('store_products.store_product_id = store_product.id');
})
->orderBy('id', 'desc')->paginate($perPage)
In my database are 20K rows, and this select execute about 65 seconds.
Im using laravel debugbar. Queries dump 2 select:
select count(*) as aggregate from `store_product` where `store_product`.`deleted_at` is null and `user_id` = '20' and not exists (select 1 from `store_products` where store_products.store_product_id = store_product.id)65.88s
select * from `store_product` where `store_product`.`deleted_at` is null and `user_id` = '20' and not exists (select 1 from `store_products` where store_products.store_product_id = store_product.id) order by `id` desc limit 24 offset 0
Why laravel do select count(*) as aggregate? How to optimizate this query?

Returning Just count of records found in MYSQL query

I have the following MYSQL query which returns the number of photos found for each record where the number of photos is greater than 0.
SELECT advert_id, (SELECT COUNT( * ) FROM advert_images b WHERE b.advert_id = adverts.advert_id) AS num_photos
FROM adverts
WHERE adverts.approve = '1'
HAVING num_photos > 0
The query works fine, but I want to just return a count of the records found. i.e. the number of records which have at least one photo. I've tried to wrap the whole query in a COUNT, but it gives an error. I want to do this in the query, and not a separate count of records found in php.
SELECT COUNT(*) AS TotalRecords
FROM
(
SELECT a.advert_id, COUNT(*) AS num_photos
FROM adverts AS a
JOIN advert_images AS i
ON i.advert_id = a.advert_id
WHERE a.approve = '1'
GROUP BY a.advert_id
HAVING num_photos > 0
) AS mq
SELECT COUNT(*) FROM (SELECT advert_id, (SELECT COUNT( * ) FROM advert_images b WHERE b.advert_id = adverts.advert_id) AS num_photos
FROM adverts
WHERE adverts.approve = '1'
HAVING num_photos > 0) AS c
This should do the trick

Categories