SQL - 如何使用UNION将三个INNER JOIN结果连接到单个结果表中?

时间:2017-11-16 15:33:48

标签: mysql sql

表格:

assistants_rating(
id INT PRIMARY KEY auto_increment,
assistant_id INT(11),
rating INT(1)
) 

另一张包含名字的助手表。我的查询如下:

(SELECT assistants.name AS assist_name , count(rating) AS OneStar FROM assistants_rating
INNER JOIN assistants on assistants.assistant_id = assistants_rating.assistant_id WHERE rating = 1)

UNION

(SELECT assistants.name AS assist_name , count(rating) AS TwoStar FROM assistants_rating
INNER JOIN assistants on assistants.assistant_id = assistants_rating.assistant_id WHERE rating = 2)

UNION

(SELECT assistants.name AS assist_name , count(rating) AS ThreeStar FROM assistants_rating
INNER JOIN assistants on assistants.assistant_id = assistants_rating.assistant_id WHERE rating = 3)

GROUP BY assistants.name,OneStar,TwoStar,ThreeStar;

让我们说我有名叫Bob和Sophie的助手,查询应该返回:

assist_name   OneStar    TwoStar    ThreeStar

  Bob            9         18          52

 Sophie          15        8           61

但相反,我得到了一个SQL语法错误,这很奇怪,因为当我单独执行每个操作时,它们都能正常工作,这让我相信我的语法很好。不仅如此,如果我UNIONTwoStar只与ThreeStarOneStar合作,而TwoStar$order = $observer->getEvent()->getCreditmemo()->getOrder(); 合作,那么$rules = [ 'hilightColorBool' => 'required|boolean', ]; if (is_bool($request->get('hilightColorBool'))) { $rules['hilightColor'] = 'required|integer|min:1|max:5'; } 的查询就会有效。

我很困惑;为什么这不起作用?

2 个答案:

答案 0 :(得分:4)

无论如何,

UNION在这里没有帮助。它做了不同的事情。

您需要的查询类似于:

SELECT 
    assistants.name AS assist_name, 
    SUM(IF(rating = 1, 1, 0)) AS OneStar,
    SUM(IF(rating = 2, 1, 0)) AS TwoStar,
    SUM(IF(rating = 3, 1, 0)) AS ThreeStar
FROM assistants_rating
    INNER JOIN assistants ON assistants.assistant_id = assistants_rating.assistant_id
GROUP BY assistants.name

答案 1 :(得分:0)

您可以使用CASE代替联盟

SELECT assistants.name AS assist_name, 
       SUM(CASE WHEN rating =1 THEN 1 ELSE 0 END) AS OneStar,
       SUM(CASE WHEN rating =2 THEN 1 ELSE 0 END) AS TwoStar,
       SUM(CASE WHEN rating =3 THEN 1 ELSE 0 END) AS ThreeStar
FROM assistants_rating
INNER JOIN assistants on assistants.assistant_id = assistants_rating.assistant_id 
GROUP BY assistants.name