Results 1 to 5 of 5

Thread: list with count of matching items (2 tbls)

  1. #1
    Join Date
    Nov 2006
    Posts
    3

    list with count of matching items (2 tbls)

    hello!

    Code:
    Tbl1
    id
    name
    
    Tbl1 ROWS
    id    name
    1     name1
    2     name2
    3     name3
    
    
    Tbl2
    id
    tbl1_id
    
    Tbl2 ROWS
    id    tbl1_id
    1     1
    2     1
    3     2

    I have 2 tables with a foreign key in Tbl2. I'm looking for the sql to list all rows in Tbl1 and count how many rows match the Tbl1.id in Tbl2 and display it in the row.
    I want the out put to read:
    id name count
    1 name1 2
    2 name2 1
    3 name3 0

    Is this possible? Thanks in advance for your help!

  2. #2
    Join Date
    Sep 2005
    Posts
    168
    SELECT a.id, a.name, COUNT(b.tbl1_id) AS count
    FROM Tbl1 a LEFT JOIN Tbl2 b ON a.id = b.tbl1_id
    GROUP BY a.id, a.name

    --HTH--

  3. #3
    Join Date
    Nov 2006
    Posts
    3
    Thank you for your response, but since I'm new to this I don't understand the meaning of "a" and "b"...
    Is a.id supposed to mean tbl1.id?

  4. #4
    Join Date
    Dec 2006
    Location
    Mumbai
    Posts
    4

    Thumbs up alias names for tables

    Quote Originally Posted by idimmu
    Thank you for your response, but since I'm new to this I don't understand the meaning of "a" and "b"...
    Is a.id supposed to mean tbl1.id?

    a and b are alias names for tbl1 and tbl2
    a.id and tbl1.id both are same
    alias names are useful when the table name is very long
    instead of type long table name you can use alias name for table


    by using table alias name you can join the table to same table
    means self join

  5. #5
    Join Date
    Nov 2006
    Posts
    3
    Thank you for the explaination! I can see where that would be helpful!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •