Note that there are some explanatory texts on larger screens.

plurals
  1. POMysql - Summing counts of multiple joined tables
    primarykey
    data
    text
    <p>I will do my best to explain this clearly. I am trying to accomplish two things, but am having trouble even getting the first to work correctly.</p> <p>I have a schema that has a member table which has foreign keys to multiple tables. In the end I am going to be drawing from about 10 tables that may or may not have records for a particular member. I am trying to get the sum of all the counts. My query looks like this:</p> <pre><code>SELECT (COUNT(tb1.member_id) + COUNT(tb2.member_id)) as total FROM members m LEFT JOIN table_1 tb1 ON tb1.member_id = m.member_id LEFT JOIN table_2 tb2 ON tb2.member_id = m.member_id WHERE m.member_id = 27 </code></pre> <p>Where 27 is the member_id of the test account I am working with. This doesn't produce accurate results and I believe it is because of the left join, it seems to be throwing things off and I am getting a total of 8 even though there are only two of each kind of record. If I eliminate one of the left joins then I get the expected result.</p> <p>Could anyone tell me how I should go about doing this?</p> <p>That is part one of my problem. The second issue is that in some of these cases I will want each result to count as either 1 or 0, that is even if there are 2 or 3 corresponding records. I was looking for something like casting a result as a bool but have not found anything. Could anyone suggest a way to do this?</p> <p>Thanks much for reading, any advice would be very much appreciated. It could be that I am approaching this problem in the wrong way, again any advice is appreciated.</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