Count total number of rows where this.row is related with rows in another tableWhat's the best practice for primary keys in tables?Foreign key referring to primary keys across multiple tables?Do I need to create indexes on foreign keys?postgreSQL Duplicate rows counting on joinShould i add a non clustered index over a clustered index table, based on this where clause and join?counting rows in two related tablescount number of hierarchical childrens in sqlCount number of rows in a table for a studentAutomatically maintain a total count of children in the parent tableCount rows that are not in another table

Inspiration for failed idea?

How can I observe Sgr A* with itelescope.net

What is the sound/audio equivalent of "unsightly"?

Board Chinese train at a different station (on-route)

What does "-1" represent in the value range for unsigned int and signed int?

How to handle inventory and story of a player leaving

Can I lend a small amount of my own money to a bank at the federal funds rate?

Is the Amazon rainforest the "world's lungs"?

Is it recommended to point out a professor's mistake during their lecture?

Why does the weaker C–H bond have a higher wavenumber than the C=O bond?

Which polygons can be turned inside out by a smooth deformation?

Why did the population of Bhutan drop by 70% between 2007 and 2008?

Can two aircraft stay on the same runway at the same time?

Are spot colors limited and why CMYK mix is not treated same as spot color mix?

Unable to enroll in insurance now because of typo in email address

Did ancient peoples ever hide their treasure behind puzzles?

Why do IR remotes influence AM radios?

Why military weather satellites?

Generic method to call API functions with simple retrial on errors

Why did Lucius make a deal out of Buckbeak hurting Draco but not about Draco being turned into a ferret?

Why are JWST optics not enclosed like HST?

Moscow SVO airport, how to avoid scam taxis without pre-booking?

Old scifi book featuring krakens attacking humans

is "prohibition against," a double negative?



Count total number of rows where this.row is related with rows in another table


What's the best practice for primary keys in tables?Foreign key referring to primary keys across multiple tables?Do I need to create indexes on foreign keys?postgreSQL Duplicate rows counting on joinShould i add a non clustered index over a clustered index table, based on this where clause and join?counting rows in two related tablescount number of hierarchical childrens in sqlCount number of rows in a table for a studentAutomatically maintain a total count of children in the parent tableCount rows that are not in another table






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I have two simple tables, parents and children. I am trying to count the number of parents who have at least one child.



create table People(
id integer unique,
name varchar(120),
primary key (id)
);

create table children(
id integer unique,
name varchar(120),
parentId integer,
primary key(id),
foreign key (parentId) references People(id)
);


This is the code I tried but it gives me the total number of children instead:



select count(*)
from (people p join children ch on ch.parentid = p.id)
having count(ch.id) > 0;









share|improve this question


























  • You can only use HAVING clause when you use GROUP BY

    – Alagu Veerappan
    Mar 27 at 22:29






  • 1





    Are you using MySQL or Postgres? These are different RDBMS, with vendor specificities. I removed the conflicting tags, please add back the relevant one.

    – GMB
    Mar 27 at 22:46







  • 1





    @GMB i am using Postgres

    – Sachihiro Takamori
    Mar 27 at 22:50

















1















I have two simple tables, parents and children. I am trying to count the number of parents who have at least one child.



create table People(
id integer unique,
name varchar(120),
primary key (id)
);

create table children(
id integer unique,
name varchar(120),
parentId integer,
primary key(id),
foreign key (parentId) references People(id)
);


This is the code I tried but it gives me the total number of children instead:



select count(*)
from (people p join children ch on ch.parentid = p.id)
having count(ch.id) > 0;









share|improve this question


























  • You can only use HAVING clause when you use GROUP BY

    – Alagu Veerappan
    Mar 27 at 22:29






  • 1





    Are you using MySQL or Postgres? These are different RDBMS, with vendor specificities. I removed the conflicting tags, please add back the relevant one.

    – GMB
    Mar 27 at 22:46







  • 1





    @GMB i am using Postgres

    – Sachihiro Takamori
    Mar 27 at 22:50













1












1








1








I have two simple tables, parents and children. I am trying to count the number of parents who have at least one child.



create table People(
id integer unique,
name varchar(120),
primary key (id)
);

create table children(
id integer unique,
name varchar(120),
parentId integer,
primary key(id),
foreign key (parentId) references People(id)
);


This is the code I tried but it gives me the total number of children instead:



select count(*)
from (people p join children ch on ch.parentid = p.id)
having count(ch.id) > 0;









share|improve this question
















I have two simple tables, parents and children. I am trying to count the number of parents who have at least one child.



create table People(
id integer unique,
name varchar(120),
primary key (id)
);

create table children(
id integer unique,
name varchar(120),
parentId integer,
primary key(id),
foreign key (parentId) references People(id)
);


This is the code I tried but it gives me the total number of children instead:



select count(*)
from (people p join children ch on ch.parentid = p.id)
having count(ch.id) > 0;






sql postgresql






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 27 at 22:50









GMB

22.3k6 gold badges11 silver badges28 bronze badges




22.3k6 gold badges11 silver badges28 bronze badges










asked Mar 27 at 22:18









Sachihiro TakamoriSachihiro Takamori

3114 silver badges14 bronze badges




3114 silver badges14 bronze badges















  • You can only use HAVING clause when you use GROUP BY

    – Alagu Veerappan
    Mar 27 at 22:29






  • 1





    Are you using MySQL or Postgres? These are different RDBMS, with vendor specificities. I removed the conflicting tags, please add back the relevant one.

    – GMB
    Mar 27 at 22:46







  • 1





    @GMB i am using Postgres

    – Sachihiro Takamori
    Mar 27 at 22:50

















  • You can only use HAVING clause when you use GROUP BY

    – Alagu Veerappan
    Mar 27 at 22:29






  • 1





    Are you using MySQL or Postgres? These are different RDBMS, with vendor specificities. I removed the conflicting tags, please add back the relevant one.

    – GMB
    Mar 27 at 22:46







  • 1





    @GMB i am using Postgres

    – Sachihiro Takamori
    Mar 27 at 22:50
















You can only use HAVING clause when you use GROUP BY

– Alagu Veerappan
Mar 27 at 22:29





You can only use HAVING clause when you use GROUP BY

– Alagu Veerappan
Mar 27 at 22:29




1




1





Are you using MySQL or Postgres? These are different RDBMS, with vendor specificities. I removed the conflicting tags, please add back the relevant one.

– GMB
Mar 27 at 22:46






Are you using MySQL or Postgres? These are different RDBMS, with vendor specificities. I removed the conflicting tags, please add back the relevant one.

– GMB
Mar 27 at 22:46





1




1





@GMB i am using Postgres

– Sachihiro Takamori
Mar 27 at 22:50





@GMB i am using Postgres

– Sachihiro Takamori
Mar 27 at 22:50












6 Answers
6






active

oldest

votes


















1
















I am trying to count the number of parents who have at least one children.




This should be as simple as:



SELECT COUNT(*) 
FROM people p
WHERE EXISTS (SELECT 1 FROM children c WHERE c.parentid = p.id)


Using EXISTS is usually the most efficient way to check that something, well, exists.






share|improve this answer
































    1















    You're close. You just need to make the check for children on a per-parent basis:



    SELECT COUNT(*) AS parents_with_children
    FROM (SELECT p.name, COUNT(c.id) AS num_children
    FROM people p
    JOIN children c ON c.parentid = p.id
    GROUP BY p.name
    HAVING COUNT(c.id) > 0) p


    Demo on dbfiddle






    share|improve this answer



























    • I get an error for this, column "num_children" does not exist, tbh i had similar solution myself and got similar error, and i could not debug it. Sorry for my noob questions.

      – Sachihiro Takamori
      Mar 27 at 22:46











    • @SachihiroTakamori did you use a HAVING or a WHERE clause? You can't use an alias in a WHERE clause.

      – Nick
      Mar 27 at 22:51











    • @SachihiroTakamori I've corrected a minor error in the query, and added a demo of it working.

      – Nick
      Mar 27 at 22:55











    • i corrected too, adding the alias in the end but i still get the error, does it have to do because I am running postgres?

      – Sachihiro Takamori
      Mar 27 at 22:57











    • @SachihiroTakamori ah... when I answered the question it was tagged MySQL... I've updated the query so it will work on PostgreSQL

      – Nick
      Mar 27 at 22:59


















    0















    SELECT COUNT(*),p.*
    FROM People p JOIN children c ON c.parnetId=p.id
    WHERE NOT c.parnetId IS NULL
    GROUP BY (p.id)


    (no need for having since it only joins existing children anyways)






    share|improve this answer
































      0















      select count(p.*)
      from people p inner join children ch
      on ch.parentid = p.id





      share|improve this answer






















      • 2





        Would you add some explanation, please ?

        – Vega
        Mar 27 at 22:47


















      0















      You could try something like this,



      SELECT COUNT(DISTINCT children.parentid)
      FROM People
      INNER JOIN children
      ON children.parentid = people.id;





      share|improve this answer
































        0















        With EXISTS:



        select count(distinct p.id) counter from people p
        where exists (
        select 1 from children
        where parentid = p.id
        )


        or even better:



        select count(distinct parentid) counter 
        from children


        because all the info you need is in the table children, so just count the distinct values in column parentid






        share|improve this answer



























        • What does select 1 from children means?

          – Sachihiro Takamori
          Mar 27 at 22:37











        • What matters here is EXISTS. If there is at least 1 row returned then the condition is true. Select 1 could be select 0 or select * it does not matter as long as 1 row is returned.

          – forpas
          Mar 27 at 22:39






        • 1





          Read more here: dev.mysql.com/doc/refman/8.0/en/…

          – forpas
          Mar 27 at 22:40













        Your Answer






        StackExchange.ifUsing("editor", function ()
        StackExchange.using("externalEditor", function ()
        StackExchange.using("snippets", function ()
        StackExchange.snippets.init();
        );
        );
        , "code-snippets");

        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "1"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader:
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        ,
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );













        draft saved

        draft discarded


















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55387340%2fcount-total-number-of-rows-where-this-row-is-related-with-rows-in-another-table%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        6 Answers
        6






        active

        oldest

        votes








        6 Answers
        6






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        1
















        I am trying to count the number of parents who have at least one children.




        This should be as simple as:



        SELECT COUNT(*) 
        FROM people p
        WHERE EXISTS (SELECT 1 FROM children c WHERE c.parentid = p.id)


        Using EXISTS is usually the most efficient way to check that something, well, exists.






        share|improve this answer





























          1
















          I am trying to count the number of parents who have at least one children.




          This should be as simple as:



          SELECT COUNT(*) 
          FROM people p
          WHERE EXISTS (SELECT 1 FROM children c WHERE c.parentid = p.id)


          Using EXISTS is usually the most efficient way to check that something, well, exists.






          share|improve this answer



























            1














            1










            1










            I am trying to count the number of parents who have at least one children.




            This should be as simple as:



            SELECT COUNT(*) 
            FROM people p
            WHERE EXISTS (SELECT 1 FROM children c WHERE c.parentid = p.id)


            Using EXISTS is usually the most efficient way to check that something, well, exists.






            share|improve this answer














            I am trying to count the number of parents who have at least one children.




            This should be as simple as:



            SELECT COUNT(*) 
            FROM people p
            WHERE EXISTS (SELECT 1 FROM children c WHERE c.parentid = p.id)


            Using EXISTS is usually the most efficient way to check that something, well, exists.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 27 at 22:33









            GMBGMB

            22.3k6 gold badges11 silver badges28 bronze badges




            22.3k6 gold badges11 silver badges28 bronze badges


























                1















                You're close. You just need to make the check for children on a per-parent basis:



                SELECT COUNT(*) AS parents_with_children
                FROM (SELECT p.name, COUNT(c.id) AS num_children
                FROM people p
                JOIN children c ON c.parentid = p.id
                GROUP BY p.name
                HAVING COUNT(c.id) > 0) p


                Demo on dbfiddle






                share|improve this answer



























                • I get an error for this, column "num_children" does not exist, tbh i had similar solution myself and got similar error, and i could not debug it. Sorry for my noob questions.

                  – Sachihiro Takamori
                  Mar 27 at 22:46











                • @SachihiroTakamori did you use a HAVING or a WHERE clause? You can't use an alias in a WHERE clause.

                  – Nick
                  Mar 27 at 22:51











                • @SachihiroTakamori I've corrected a minor error in the query, and added a demo of it working.

                  – Nick
                  Mar 27 at 22:55











                • i corrected too, adding the alias in the end but i still get the error, does it have to do because I am running postgres?

                  – Sachihiro Takamori
                  Mar 27 at 22:57











                • @SachihiroTakamori ah... when I answered the question it was tagged MySQL... I've updated the query so it will work on PostgreSQL

                  – Nick
                  Mar 27 at 22:59















                1















                You're close. You just need to make the check for children on a per-parent basis:



                SELECT COUNT(*) AS parents_with_children
                FROM (SELECT p.name, COUNT(c.id) AS num_children
                FROM people p
                JOIN children c ON c.parentid = p.id
                GROUP BY p.name
                HAVING COUNT(c.id) > 0) p


                Demo on dbfiddle






                share|improve this answer



























                • I get an error for this, column "num_children" does not exist, tbh i had similar solution myself and got similar error, and i could not debug it. Sorry for my noob questions.

                  – Sachihiro Takamori
                  Mar 27 at 22:46











                • @SachihiroTakamori did you use a HAVING or a WHERE clause? You can't use an alias in a WHERE clause.

                  – Nick
                  Mar 27 at 22:51











                • @SachihiroTakamori I've corrected a minor error in the query, and added a demo of it working.

                  – Nick
                  Mar 27 at 22:55











                • i corrected too, adding the alias in the end but i still get the error, does it have to do because I am running postgres?

                  – Sachihiro Takamori
                  Mar 27 at 22:57











                • @SachihiroTakamori ah... when I answered the question it was tagged MySQL... I've updated the query so it will work on PostgreSQL

                  – Nick
                  Mar 27 at 22:59













                1














                1










                1









                You're close. You just need to make the check for children on a per-parent basis:



                SELECT COUNT(*) AS parents_with_children
                FROM (SELECT p.name, COUNT(c.id) AS num_children
                FROM people p
                JOIN children c ON c.parentid = p.id
                GROUP BY p.name
                HAVING COUNT(c.id) > 0) p


                Demo on dbfiddle






                share|improve this answer















                You're close. You just need to make the check for children on a per-parent basis:



                SELECT COUNT(*) AS parents_with_children
                FROM (SELECT p.name, COUNT(c.id) AS num_children
                FROM people p
                JOIN children c ON c.parentid = p.id
                GROUP BY p.name
                HAVING COUNT(c.id) > 0) p


                Demo on dbfiddle







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 27 at 22:59

























                answered Mar 27 at 22:30









                NickNick

                51.6k14 gold badges25 silver badges46 bronze badges




                51.6k14 gold badges25 silver badges46 bronze badges















                • I get an error for this, column "num_children" does not exist, tbh i had similar solution myself and got similar error, and i could not debug it. Sorry for my noob questions.

                  – Sachihiro Takamori
                  Mar 27 at 22:46











                • @SachihiroTakamori did you use a HAVING or a WHERE clause? You can't use an alias in a WHERE clause.

                  – Nick
                  Mar 27 at 22:51











                • @SachihiroTakamori I've corrected a minor error in the query, and added a demo of it working.

                  – Nick
                  Mar 27 at 22:55











                • i corrected too, adding the alias in the end but i still get the error, does it have to do because I am running postgres?

                  – Sachihiro Takamori
                  Mar 27 at 22:57











                • @SachihiroTakamori ah... when I answered the question it was tagged MySQL... I've updated the query so it will work on PostgreSQL

                  – Nick
                  Mar 27 at 22:59

















                • I get an error for this, column "num_children" does not exist, tbh i had similar solution myself and got similar error, and i could not debug it. Sorry for my noob questions.

                  – Sachihiro Takamori
                  Mar 27 at 22:46











                • @SachihiroTakamori did you use a HAVING or a WHERE clause? You can't use an alias in a WHERE clause.

                  – Nick
                  Mar 27 at 22:51











                • @SachihiroTakamori I've corrected a minor error in the query, and added a demo of it working.

                  – Nick
                  Mar 27 at 22:55











                • i corrected too, adding the alias in the end but i still get the error, does it have to do because I am running postgres?

                  – Sachihiro Takamori
                  Mar 27 at 22:57











                • @SachihiroTakamori ah... when I answered the question it was tagged MySQL... I've updated the query so it will work on PostgreSQL

                  – Nick
                  Mar 27 at 22:59
















                I get an error for this, column "num_children" does not exist, tbh i had similar solution myself and got similar error, and i could not debug it. Sorry for my noob questions.

                – Sachihiro Takamori
                Mar 27 at 22:46





                I get an error for this, column "num_children" does not exist, tbh i had similar solution myself and got similar error, and i could not debug it. Sorry for my noob questions.

                – Sachihiro Takamori
                Mar 27 at 22:46













                @SachihiroTakamori did you use a HAVING or a WHERE clause? You can't use an alias in a WHERE clause.

                – Nick
                Mar 27 at 22:51





                @SachihiroTakamori did you use a HAVING or a WHERE clause? You can't use an alias in a WHERE clause.

                – Nick
                Mar 27 at 22:51













                @SachihiroTakamori I've corrected a minor error in the query, and added a demo of it working.

                – Nick
                Mar 27 at 22:55





                @SachihiroTakamori I've corrected a minor error in the query, and added a demo of it working.

                – Nick
                Mar 27 at 22:55













                i corrected too, adding the alias in the end but i still get the error, does it have to do because I am running postgres?

                – Sachihiro Takamori
                Mar 27 at 22:57





                i corrected too, adding the alias in the end but i still get the error, does it have to do because I am running postgres?

                – Sachihiro Takamori
                Mar 27 at 22:57













                @SachihiroTakamori ah... when I answered the question it was tagged MySQL... I've updated the query so it will work on PostgreSQL

                – Nick
                Mar 27 at 22:59





                @SachihiroTakamori ah... when I answered the question it was tagged MySQL... I've updated the query so it will work on PostgreSQL

                – Nick
                Mar 27 at 22:59











                0















                SELECT COUNT(*),p.*
                FROM People p JOIN children c ON c.parnetId=p.id
                WHERE NOT c.parnetId IS NULL
                GROUP BY (p.id)


                (no need for having since it only joins existing children anyways)






                share|improve this answer





























                  0















                  SELECT COUNT(*),p.*
                  FROM People p JOIN children c ON c.parnetId=p.id
                  WHERE NOT c.parnetId IS NULL
                  GROUP BY (p.id)


                  (no need for having since it only joins existing children anyways)






                  share|improve this answer



























                    0














                    0










                    0









                    SELECT COUNT(*),p.*
                    FROM People p JOIN children c ON c.parnetId=p.id
                    WHERE NOT c.parnetId IS NULL
                    GROUP BY (p.id)


                    (no need for having since it only joins existing children anyways)






                    share|improve this answer













                    SELECT COUNT(*),p.*
                    FROM People p JOIN children c ON c.parnetId=p.id
                    WHERE NOT c.parnetId IS NULL
                    GROUP BY (p.id)


                    (no need for having since it only joins existing children anyways)







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 27 at 22:32









                    jonathan Heindljonathan Heindl

                    6342 silver badges13 bronze badges




                    6342 silver badges13 bronze badges
























                        0















                        select count(p.*)
                        from people p inner join children ch
                        on ch.parentid = p.id





                        share|improve this answer






















                        • 2





                          Would you add some explanation, please ?

                          – Vega
                          Mar 27 at 22:47















                        0















                        select count(p.*)
                        from people p inner join children ch
                        on ch.parentid = p.id





                        share|improve this answer






















                        • 2





                          Would you add some explanation, please ?

                          – Vega
                          Mar 27 at 22:47













                        0














                        0










                        0









                        select count(p.*)
                        from people p inner join children ch
                        on ch.parentid = p.id





                        share|improve this answer















                        select count(p.*)
                        from people p inner join children ch
                        on ch.parentid = p.id






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Mar 27 at 22:46









                        Vega

                        16.3k13 gold badges47 silver badges69 bronze badges




                        16.3k13 gold badges47 silver badges69 bronze badges










                        answered Mar 27 at 22:29









                        Isaac Humberto De la Rosa MendIsaac Humberto De la Rosa Mend

                        1




                        1










                        • 2





                          Would you add some explanation, please ?

                          – Vega
                          Mar 27 at 22:47












                        • 2





                          Would you add some explanation, please ?

                          – Vega
                          Mar 27 at 22:47







                        2




                        2





                        Would you add some explanation, please ?

                        – Vega
                        Mar 27 at 22:47





                        Would you add some explanation, please ?

                        – Vega
                        Mar 27 at 22:47











                        0















                        You could try something like this,



                        SELECT COUNT(DISTINCT children.parentid)
                        FROM People
                        INNER JOIN children
                        ON children.parentid = people.id;





                        share|improve this answer





























                          0















                          You could try something like this,



                          SELECT COUNT(DISTINCT children.parentid)
                          FROM People
                          INNER JOIN children
                          ON children.parentid = people.id;





                          share|improve this answer



























                            0














                            0










                            0









                            You could try something like this,



                            SELECT COUNT(DISTINCT children.parentid)
                            FROM People
                            INNER JOIN children
                            ON children.parentid = people.id;





                            share|improve this answer













                            You could try something like this,



                            SELECT COUNT(DISTINCT children.parentid)
                            FROM People
                            INNER JOIN children
                            ON children.parentid = people.id;






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 27 at 22:48









                            Alagu VeerappanAlagu Veerappan

                            688 bronze badges




                            688 bronze badges
























                                0















                                With EXISTS:



                                select count(distinct p.id) counter from people p
                                where exists (
                                select 1 from children
                                where parentid = p.id
                                )


                                or even better:



                                select count(distinct parentid) counter 
                                from children


                                because all the info you need is in the table children, so just count the distinct values in column parentid






                                share|improve this answer



























                                • What does select 1 from children means?

                                  – Sachihiro Takamori
                                  Mar 27 at 22:37











                                • What matters here is EXISTS. If there is at least 1 row returned then the condition is true. Select 1 could be select 0 or select * it does not matter as long as 1 row is returned.

                                  – forpas
                                  Mar 27 at 22:39






                                • 1





                                  Read more here: dev.mysql.com/doc/refman/8.0/en/…

                                  – forpas
                                  Mar 27 at 22:40















                                0















                                With EXISTS:



                                select count(distinct p.id) counter from people p
                                where exists (
                                select 1 from children
                                where parentid = p.id
                                )


                                or even better:



                                select count(distinct parentid) counter 
                                from children


                                because all the info you need is in the table children, so just count the distinct values in column parentid






                                share|improve this answer



























                                • What does select 1 from children means?

                                  – Sachihiro Takamori
                                  Mar 27 at 22:37











                                • What matters here is EXISTS. If there is at least 1 row returned then the condition is true. Select 1 could be select 0 or select * it does not matter as long as 1 row is returned.

                                  – forpas
                                  Mar 27 at 22:39






                                • 1





                                  Read more here: dev.mysql.com/doc/refman/8.0/en/…

                                  – forpas
                                  Mar 27 at 22:40













                                0














                                0










                                0









                                With EXISTS:



                                select count(distinct p.id) counter from people p
                                where exists (
                                select 1 from children
                                where parentid = p.id
                                )


                                or even better:



                                select count(distinct parentid) counter 
                                from children


                                because all the info you need is in the table children, so just count the distinct values in column parentid






                                share|improve this answer















                                With EXISTS:



                                select count(distinct p.id) counter from people p
                                where exists (
                                select 1 from children
                                where parentid = p.id
                                )


                                or even better:



                                select count(distinct parentid) counter 
                                from children


                                because all the info you need is in the table children, so just count the distinct values in column parentid







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Mar 27 at 22:52

























                                answered Mar 27 at 22:32









                                forpasforpas

                                41.9k6 gold badges12 silver badges33 bronze badges




                                41.9k6 gold badges12 silver badges33 bronze badges















                                • What does select 1 from children means?

                                  – Sachihiro Takamori
                                  Mar 27 at 22:37











                                • What matters here is EXISTS. If there is at least 1 row returned then the condition is true. Select 1 could be select 0 or select * it does not matter as long as 1 row is returned.

                                  – forpas
                                  Mar 27 at 22:39






                                • 1





                                  Read more here: dev.mysql.com/doc/refman/8.0/en/…

                                  – forpas
                                  Mar 27 at 22:40

















                                • What does select 1 from children means?

                                  – Sachihiro Takamori
                                  Mar 27 at 22:37











                                • What matters here is EXISTS. If there is at least 1 row returned then the condition is true. Select 1 could be select 0 or select * it does not matter as long as 1 row is returned.

                                  – forpas
                                  Mar 27 at 22:39






                                • 1





                                  Read more here: dev.mysql.com/doc/refman/8.0/en/…

                                  – forpas
                                  Mar 27 at 22:40
















                                What does select 1 from children means?

                                – Sachihiro Takamori
                                Mar 27 at 22:37





                                What does select 1 from children means?

                                – Sachihiro Takamori
                                Mar 27 at 22:37













                                What matters here is EXISTS. If there is at least 1 row returned then the condition is true. Select 1 could be select 0 or select * it does not matter as long as 1 row is returned.

                                – forpas
                                Mar 27 at 22:39





                                What matters here is EXISTS. If there is at least 1 row returned then the condition is true. Select 1 could be select 0 or select * it does not matter as long as 1 row is returned.

                                – forpas
                                Mar 27 at 22:39




                                1




                                1





                                Read more here: dev.mysql.com/doc/refman/8.0/en/…

                                – forpas
                                Mar 27 at 22:40





                                Read more here: dev.mysql.com/doc/refman/8.0/en/…

                                – forpas
                                Mar 27 at 22:40

















                                draft saved

                                draft discarded
















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55387340%2fcount-total-number-of-rows-where-this-row-is-related-with-rows-in-another-table%23new-answer', 'question_page');

                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                                은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현