?
Solved

is there a way to do this in  single query?

Posted on 2012-03-29
2
Medium Priority
?
432 Views
Last Modified: 2012-03-29
hello,
i have a pretty simple table.

the parent tc_group record has a parentID of 0. A tc_group can have children and that would be indicated by the parentID

CREATE TABLE `tc_group` (
      `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
      `userID` INT(10) UNSIGNED NULL DEFAULT NULL,
      `group_name` VARCHAR(50) NULL DEFAULT NULL,
      `parentID` INT(10) UNSIGNED NULL DEFAULT '0',
      `idx` SMALLINT NULL DEFAULT '0',
      PRIMARY KEY (`id`)


What i would like to do but can not seem to think of a way to do it is with One query get all the rows that have a parentID = 0  and a count of how many rows each of those records have were its own ID is the parentID. So get all the parents and a count of their children with a single query.

I am thinking maybe i could do this with a subselect but jsut can't seem to get my head around it
thanks for any help
0
Comment
Question by:paries
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 58

Accepted Solution

by:
HainKurt earned 2000 total points
ID: 37784275
try this:

select g.*, (select count(1) from tc_group g2 where g2.parentID=g.id) as ChildCount
from tc_group g
where parentid=0
0
 

Author Closing Comment

by:paries
ID: 37784283
thanks
0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This post contains step-by-step instructions for setting up alerting in Percona Monitoring and Management (PMM) using Grafana.
In part one, we reviewed the prerequisites required for installing SQL Server vNext. In this part we will explore how to install Microsoft's SQL Server on Ubuntu 16.04.
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…
Suggested Courses

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question