SQL连接3个表中的数据

时间:2017-08-02 21:29:12

标签: php mysql sql join

我有3张桌子:
skill_categories(id, name) - 类别列表
skills(id, skill_category_id, name) - 每个技能类别的子类别
contributors(id, name, skill_id_1, skill_id_2, skill_id_3) - 一个人最多可以拥有3项技能

我想查询贡献者中每个skill_category_id, skill_category_name, skill_id and skill_name字段的skill_id

根据我的阅读,我认为可以使用SQL JOIN来实现这一点,并编写了这样的查询。

SELECT s.skill_category_id AS skill_category_id, 
       sc.name AS skill_category_name,
       s.id AS skill_id, 
       s.name AS name
FROM skills AS s
INNER JOIN skill_categories AS sc 
      ON s.skill_category_id = sc.id
INNER JOIN contributors AS c
      ON c.skill_id_1 = s.id
      OR c.skill_id_2 = s.id
      OR c.skill_id_3 = s.id
WHERE c.id = $id
ORDER BY s.name, sc.name ASC

这是执行此类查询的最佳方式吗?

1 个答案:

答案 0 :(得分:0)

不,这不是最佳方式 - 尤其是从性能角度来看。 OR(或IN)是联接的性能杀手。

最好添加更多联接,每个技能类别一个。所以,这应该有更好的表现:

SELECT s.skill_category_id AS skill_category_id,  sc.name AS skill_category_name,
       s.id AS skill_id,  s.name AS name
FROM skills s INNER JOIN
     skill_categories sc 
     ON s.skill_category_id = sc.id LEFT JOIN
     contributors c1
     ON c.skill_id_1 = s.id LEFT JOIN
     contributors c2
     ON c1.skill_id_2 = s.id LEFT JOIN
     contributors c3
     ON c3.skill_id_3 = s.id
WHERE $id in (c1.id, c2.id, c3.id)
ORDER BY s.name, sc.name ASC

如果每个技能都有单独的行,而不是单独的列,则查询会更简单。