Note that there are some explanatory texts on larger screens.

plurals
  1. POMySQL select count with join
    primarykey
    data
    text
    <p>I am trying to get a list of data from multiple tables in a view for analytics - most of the data comes from one table and then I need to get the counts from multiple other tables to show number of logins, number of users and so on.</p> <p>I am using the below query (simplified to show only some rows and one join):</p> <pre><code>Select companies.company_name, companies.last_login, companies.last_ip, (SELECT COUNT(*) FROM auditing_master GROUP BY company_id) AS audit_count From companies Left Join auditing_master On auditing_master.company_id = companies.id Group by companies.id </code></pre> <p>When I run this I get an error:</p> <pre><code>#2014 - Commands out of sync; you can't run this command now </code></pre> <p>If I run it without the GROUP BY in the SELECT COUNT (*) then it doesn't give any error but it returns a count of all entries in the auditing_master table regardless of which company it refers to.</p> <p>How can I get a single query to show me the required data from the companies table whilst also showing a total from auditing master (and others) grouped by the company ID?</p> <p><strong>Edit</strong></p> <p>Code when using multiple count/joins:</p> <pre><code>Select c.company_name, c.last_login, c.last_ip, COUNT(am.company_id) AS audit_count, COUNT(u.company_id) AS users, COUNT(e.company_id) AS employees From companies c Left Join auditing_master am On am.company_id = c.id Left Join users u On u.company_id = c.id Left Join employees e On e.company_id = c.id Group by c.id </code></pre> <p>This query locally in PHPMyAdmin on WAMP with only around 10 companies takes 7 seconds to complete and give "meanngless" results that don't correlate to anything.</p> <p>Thanks</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.
    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