【问题标题】:Efficient SQL query with subquery and multiple joins具有子查询和多个连接的高效 SQL 查询
【发布时间】:2011-09-10 11:23:25
【问题描述】:

我有以下 SQL 查询,它执行子查询并连接两个表,然后与主表连接:

SELECT a.id, cgso.sf_guard_user_id as cgso, cgal.sf_guard_user_id as cgal
FROM table_a a
JOIN (  SELECT cgso.sf_guard_user_id, cgso.speciality_id
        FROM table_c g
        JOIN  table_b as  cgso
            ON g.user_id = cgso.sf_guard_user_id and g.group_id = 2) as cgso
    ON a.speciality_id = cgso.speciality_id
JOIN (  SELECT cgal.sf_guard_user_id, cgal.speciality_id
        FROM table_c g
        JOIN  table_b as  cgal
            ON g.user_id = cgal.sf_guard_user_id and g.group_id = 1) as cgal
    ON a.speciality_id = cgal.speciality_id

查询的输出是:

id | cgso | cgal
----------------
 1 |  2   | 54

输出很好并且符合预期,但是有没有更有效的方法来获得相同的输出?任何提示或建议将不胜感激。

谢谢

【问题讨论】:

  • 这可能应该在codereview 上提出,这是一个有关改进(如果可能)已经工作的代码的问题的站点。 StackOverflow 更多的是用代码解决问题。

标签: mysql sql join subquery


【解决方案1】:

您应该能够简化连接...

SELECT a.id, cgso.sf_guard_user_id as cgso, cgal.sf_guard_user_id as cgal
FROM table_a a
INNER JOIN table_c g2 ON g1.group_id = 2
INNER JOIN table_b cgso ON g2.user_id = cgso.sf_guard_user_id  AND cgso.specialty_id = a.specialty_id
INNER JOIN table_c g1 ON g1.user_id = 1
INNER JOIN table_b cgal ON g1.user_id = cgal.sf_guard_user_id AND cgal.specialty_id = a.specialty_id

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-20
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    • 2021-12-19
    相关资源
    最近更新 更多