Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I count all the records in the both tables in a 1:n relationship in 1 query?
    primarykey
    data
    text
    <p>I'm guessing this a fairly easy question, but I've run into this problem a number of times and I can't find a solution either through searching (maybe I don't know what to search for) or trial and error.</p> <p>I have the following table structure and data:</p> <pre><code>CREATE TABLE `table_a` ( `id` int(11) NOT NULL auto_increment, `table_b_id` int(11) NOT NULL, `field` varchar(10) NOT NULL, PRIMARY KEY (`id`), KEY `table_b_id` (`table_b_id`) ); INSERT INTO `table_a` VALUES(1, 1, 'test 1'); INSERT INTO `table_a` VALUES(2, 1, 'test 2'); INSERT INTO `table_a` VALUES(3, 0, 'test 3'); CREATE TABLE `table_b` ( `id` int(11) NOT NULL auto_increment, `name` varchar(10) NOT NULL, PRIMARY KEY (`id`) ); INSERT INTO `table_b` VALUES(1, 'value 1'); INSERT INTO `table_b` VALUES(2, 'value 2'); </code></pre> <p>As you can see, id 2 in <code>table_b</code> is not used in <code>table_a</code> and id 3 in <code>table_a</code> has a value of 0 for <code>table_b_id</code>. What I want to do is retrieve a count of the number of times each value in b is used in <code>table_a</code>, including 2 from <code>table_b</code> and count of all the values not in <code>table_b</code>.</p> <p>I have come up with the following query:</p> <pre><code>SELECT b.name, COUNT(a.id) AS number FROM table_a AS a LEFT JOIN table_b AS b ON (b.id = a.table_b_id) GROUP BY a.table_b_id </code></pre> <p>But it obviously only returns the following:</p> <pre><code>name number ----------------- null 1 value 1 2 </code></pre> <p>How can I get the following, with only SQL:</p> <pre><code>name number ----------------- null 1 value 1 2 value 2 0 </code></pre> <p>I am using MySQL. I'm guessing the answer is simple.</p> <p><strong>Edit:</strong> Is there no other way other than a union'd query?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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