首页 > 解决方案 > 使用三表mysql连接查询

问题描述

我有三个表 p_c_n_details、supplier_details、pcn_type。我尝试使用这些表连接查询。但是group by有错误。

我的查询:

SELECT pcn_type.name, p_c_n_details.SupplierName, COUNT(p_c_n_details.JPN_ID) 
FROM pcn_type LEFT OUTER JOIN p_c_n_details RIGHT OUTER JOIN supplier_details 
ON p_c_n_details.type = pcn_type.name AND p_c_n_details.SupplierName = 
supplier_details.SupplierName GROUP BY 
pcn_type.name,supplier_details.SupplierName;

pcn_type 表:

id    |    name
-------------------------
1          Process Change
2          Design Change
3          EOL

供应商详细信息表:

id    |    SupplierName
------------------------
1          abc
2          def
3          ghi

p_c_n_details 表:

id.   |    SupplierName    |    type           |    JPN_ID
1          abc                  Process Change      0023
2          abc                  Process Change      0024
3          abc                  Process Change      0025
4          abc                  Design Change       0026
5          abc                  Design Change       0027
6          def                  Process Change      0028
7          def                  Process Change      0029
8          def                  EOL                 0030
9          def                  EOL                 0031

预期结果:

name            |    supplier  |    total
------------------------------------------------------    
Process Change       abc            03
Design Change        abc            02
EOL                  abc             0
Process Change       def            02
Design Change        def             0
EOL                  def            02

我得到的错误:

#1064 - You have an error in your SQL syntax; check the manual that 
corresponds to your MySQL server version for the right syntax to use near 
'GROUP BY pcn_type.name,supplier_details.SupplierName LIMIT 0, 25' at line 1

我需要在查询中更改以纠正错误。

标签: mysqlgroup-by

解决方案


您的查询中有错误,请检查以下更新的查询并与您的旧查询进行比较:

SELECT
    pcn_type. NAME,
    p_c_n_details.SupplierName,
    COUNT(p_c_n_details.id)
FROM
    pcn_type
LEFT OUTER JOIN p_c_n_details ON p_c_n_details.type = pcn_type.name 
RIGHT OUTER JOIN supplier_details ON p_c_n_details.Suppliername = supplier_details.SupplierName
GROUP BY p_c_n_details.Suppliername, p_c_n_details.type;

推荐阅读