Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
984 views
in Technique[技术] by (71.8m points)

count results different tables single query mysql php

I have the user id_user=5 who has posts in three different tables

 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

   $count_questions = $result["count_questions"];

but it doesnt seems to work

question from:https://stackoverflow.com/questions/65617660/count-results-different-tables-single-query-mysql-php

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.

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
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...