3

我正在尝试将两个表连接到我的查询中,并计算每个连接的匹配行数。不过,它似乎返回了错误的结果。结果似乎翻了一番。这是查询

SELECT *, COUNT(car_id) AS numCars, COUNT(van_id) AS numVans 
            FROM company_branch
            LEFT JOIN car ON car_branchid = company_branch_id
            LEFT JOIN van ON van_branchid = company_branch_id
            WHERE company_branch_userid = 1

            GROUP BY company_branch_id, 
            ORDER BY company_branch_active DESC, company_branch_name ASC
4

1 回答 1

4

我假设这car_id是表上的主键,car并且van_id是表上的主键van。在这种情况下,使用DISTINCT分别获取每个组中的计数。尝试这个:

SELECT *, COUNT(DISTINCT car_id) AS numCars, COUNT(DISTINCT van_id) AS numVans 
        FROM company_branch
        LEFT JOIN car ON car_branchid = company_branch_id
        LEFT JOIN van ON van_branchid = company_branch_id
        WHERE company_branch_userid = 1

        GROUP BY company_branch_id, 
        ORDER BY company_branch_active DESC, company_branch_name ASC
于 2012-11-09T00:12:04.610 回答