Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>For your first question:</p> <pre><code>SELECT A.ID, A.Name, COUNT(ab.B_ID) AS bcount FROM A LEFT JOIN A_B_Link ab ON (ab.A_ID = A.ID) GROUP BY A.ID, A.Name; </code></pre> <p>This outputs one row per row of A, with the count of matching B's. Note that you must list all columns of A in the GROUP BY statement; there's no way to use a wildcard here.</p> <p>An alternate solution is to use a correlated subquery, as @Ray Booysen shows:</p> <pre><code>SELECT A.*, (SELECT COUNT(*) FROM A_B_Link WHERE A_B_Link.A_ID = A.A_ID) AS bcount FROM A; </code></pre> <p>This works, but correlated subqueries aren't very good for performance.</p> <p>For your second question, you need something like MySQL's <code>GROUP_CONCAT()</code> aggregate function. In MySQL, you can get a comma-separated list of <code>B.Name</code> per row of A like this:</p> <pre><code>SELECT A.*, GROUP_CONCAT(B.Name) AS bname_list FROM A LEFT OUTER JOIN A_B_Link ab ON (A.ID = ab.A_ID) LEFT OUTER JOIN B ON (ab.B_ID = B.ID) GROUP BY A.ID; </code></pre> <p>There's no easy equivalent in Microsoft SQL Server. Check here for another question on SO about this: "<a href="https://stackoverflow.com/questions/451415/simulating-groupconcat-mysql-function-in-ms-sql-server-2005">Simulating group_concat MySQL function in MS SQL Server 2005?</a>"</p> <p>Or Google for '<a href="http://www.google.com/search?q=microsoft+sql+server+%22group_concat%22" rel="nofollow noreferrer">microsoft SQL server "group_concat"</a>' for a variety of other solutions.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload