[英]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. 我有5张桌子:a,b,c,d和e。
Each table is joined by an INNER JOIN on the id field. 每个表都由ID字段上的INNER JOIN连接。
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 *"
和group by
,并且在某些数据库中会引发错误,我将执行以下操作:
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... 基本思想是添加一个外部查询并在其上使用
group by
...
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 *. 该查询应使用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. 我没有在您的查询中注意到GROUP BY。
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. 这将为您提供查询返回的行数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.