catfan / Medoo

The lightweight PHP database framework to accelerate the development.
https://medoo.in
MIT License
4.84k stars 1.15k forks source link

Count within select query #751

Closed sourabhbajaj closed 6 years ago

sourabhbajaj commented 6 years ago

Consider this usecase:

I have a set of questions and each question has some votes and answers. I am showing all the questions on one page and I want to show the count of upvotes, downvotes and answers with each question.

Look at this query: select question.id, question.text, count(answer.id) from question left join answer on question.id=answer.questionId group by question.id

Can't figure out how to do this with Medoo.

catfan commented 6 years ago
$data = $database->select('question', [
    '[>]answer' => ['id' => 'questionId']
], [
    'question.id',
    'question.text',
    'answerCount' => Medoo::raw('COUNT(<answer.id>)')
], [
    'GROUP' => 'question.id'
]);

Query Output:

SELECT `question`.`id`,`question`.`text`,COUNT(`answer`.`id`) AS `count` FROM `question` LEFT JOIN `answer` ON `question`.`id` = `answer`.`questionId` GROUP BY `question`.`id`
sourabhbajaj commented 6 years ago

Thank you for the help. This is what I was looking for.