简体   繁体   中英

How do I write a My(SQL) query that counts from multiple tables based on specific WHERE clause criteria

I have 5 tables: a, b, c, d and e.

Each table is joined by an INNER JOIN on the id field.

My query is working perfectly fine as it is but I need to enhance it to count the result so I can echo it to the screen. I have not been able to get the count working.

There are very specific fields I am querying:

state_nm
status
loc_type

These are all parameters I enter manually into the query like so:

$_POST["state_nm"] = 'AZ'; ... // and for all other below values..

SELECT *
FROM main_table AS a
INNER JOIN table_1 AS b ON a.id = b.id
INNER JOIN table_2 AS c ON b.id = c.id
INNER JOIN blm table_3 AS d ON c.id = d.id
INNER JOIN table_4 AS e ON d.id = e.id
WHERE a.trq != ''
   AND b.state_nm = '".$_POST["state_nm"]."'
   AND b.loc_type LIKE \ "%".$_ POST ["loc_type"]."%\"
   AND b.STATUS = '".$_POST["status"]."'
GROUP BY b.NAME
ORDER BY c.county ASC;

not sure I get exactly what is your goal here. anyway, using "select *" and group by in the same query is not recommended and in some databases will raise an error what I would do is something like that:

select a.name, count(*) from (
SELECT * FROM main_table as a 

INNER JOIN table_1 as b 

ON a.id=b.id

INNER JOIN table_2 as c

ON b.id=c.id 

INNER JOIN blm table_3 as d 

ON c.id=d.id 

INNER JOIN table_4 as e

ON d.id=e.id  

WHERE a.trq != '' 

AND b.state_nm = '".$_POST["state_nm"]."'  

AND b.loc_type LIKE \"%".$_POST["loc_type"]."%\"  

AND  b.status = '".$_POST["status"]."' 
)a
group by a.name

the basic idea is to add an outer query and use group by on it...

hopefully this solves your problem.

In place of

SELECT *

in your query, you could replace that with

SELECT COUNT(*)

That query should return the number of rows that would be in the resultset for the query using SELECT *. Pretty easy to test, and compare the results.

I think that answers the question you asked. If not, I didn't understand your question.


I didn't notice the GROUP BY in your query.

If you want to get a count of rows returned by that query, wrap it in outer query.

SELECT COUNT(1) FROM (
  /* your query here */
 ) c

That will give you a count of rows returned by your query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM