[英]count results different tables single query mysql php
I have the user id_user=5
who has posts in three different tables我的用户id_user=5
在三个不同的表中都有帖子
questions (id_post | id_user ...) (7 posts)
marketplace (id_post | id_user ...) (9 posts)
jobs (id_post | id_user ...) (3 posts)
So I want to count, using a single query, the number of posts he has in each table所以我想用一个查询来计算他在每个表中的帖子数
This is what I have so far...but it doesnt seems to work这是我到目前为止所拥有的......但它似乎不起作用
(SELECT
COUNT(p.*) as count_questions
FROM $table_questions as p
WHERE p.id_user = :id_user1
)
UNION
(
SELECT
COUNT(m.*) as count_marketplace
FROM $table_marketplace as m
WHERE m.id_user = :id_user2
)
UNION
(SELECT
COUNT(e.*) as count_jobs
FROM $table_jobs as e
WHERE e.id_user = :id_user3
)
what am doing wrong?做错了什么?
I was expecting to retrieve in php like this我期待像这样在 php 中检索
$count_questions = $result["count_questions"];
but it doesnt seems to work但它似乎不起作用
SELECT COUNT(id_user) as counter
FROM $table_questions WHERE id_user = :id_user1
UNION
SELECT COUNT(id_user) as counter
FROM $table_marketplace WHERE id_user = :id_user2
UNION
SELECT COUNT(id_user) as counter
FROM $table_jobs WHERE id_user = :id_user3
Will return 3 rows each with the count, you have to give all the counts the same alias.将返回 3 行,每行带有计数,您必须为所有计数提供相同的别名。
If you want to maybe identfy each result row specifically add another column as an identifier如果您想识别每个结果行,专门添加另一列作为标识符
SELECT 'Questions' as what, COUNT(id_user) as counter
FROM $table_questions WHERE id_user = :id_user1
UNION
SELECT 'Marketplace' as what, COUNT(id_user) as counter
FROM $table_marketplace WHERE id_user = :id_user2
UNION
SELECT 'Jobs' as what, COUNT(id_user) as counter
FROM $table_jobs WHERE id_user = :id_user3
Will give something like会给出类似的东西
what count
Questions 7
Marketplace 9
Jobs 3
And you can retrieve them as您可以将它们检索为
$array = $stmt->fetch_all();
You will get an array like你会得到一个像
Array
(
[Questions] => 7
[Marketplace] => 9
[Jobs] => 3
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.