繁体   English   中英

MySQL:联接多个表

[英]MySQL: JOIN multiple tables

我有以下查询,我试图在2个条件下联接2个表(“ Industry”,“ Country”),但这给了我以下错误

错误代码:1054。“ on子句”中的未知列“ i.id”

有人知道我该怎么解决吗?

SELECT c.name AS country_name, i.name as industry_name, num_projects, num_consultants, admin_rating
    FROM    industry i, country c 
    JOIN   (SELECT   pc.country_id, pi.industry_id, COUNT(p.id) AS num_projects
            FROM     project p, project_country pc, project_industry pi
            where p.id = pc.project_id and pi.project_id=p.id
            GROUP BY pc.country_id,pi.industry_id) x ON x.country_id = c.id  and x.industry_id=i.id
    JOIN   (SELECT   u.country_id,ie.industry_id, COUNT(u.id) AS num_consultants  
            FROM     user u, consultant_profile, industry_experience ie
            WHERE    u.is_active = 1 AND u.type = 0 and
                     ie.consultant_profile_id= consultant_profile.id 
                     and u.id= consultant_profile.id 
            GROUP BY u.country_id,ie.industry_id) y ON y.country_id = c.id and y.industry_id = i.id order by num_projects DESC limit 20;

EDIT的表结构如下:

  • 行业 -ID
  • project_industry -Industry_id,project_id
  • Industry_experience -consultant_profile_id,industry_id
  • consultant_profile -ID,用户ID

由于您仍然不提供任何SQL提琴,因此您可以从我的SQL提琴开始:

http://sqlfiddle.com/#!9/6c0569/1

SELECT   pc.country_id, pi.industry_id, 
  COUNT(p.id) AS num_projects,
  COUNT(u.id) AS num_consultants
  FROM   project p
INNER JOIN project_country pc
ON p.id = pc.project_id
INNER JOIN project_industry pi
ON pi.project_id=p.id
INNER JOIN `user` u
ON u.is_active = 1 AND u.type = 0 
   and u.country_id = pc.country_id
INNER JOIN industry_experience ie
ON u.id = ie.consultant_profile_id
  AND ie.industry_id = pi.industry_id
GROUP BY pc.country_id, pi.industry_id

如果您将一些数据添加到该提琴中,我们可以进行更深入的讨论

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM