SQL连接表到选定的记录

时间:2014-09-12 11:29:53

标签: mysql sql subquery left-join

示例:

SELECT SUM(SALARY) FROM (SELECT * FROM table1 WHERE id > 10) a LEFT JOIN table2 b on a.person = b.person

我希望只将table2记录连接到(SELECT * FROM table1 WHERE id > 10)条记录,我的例子不正确。

table1包含100mln记录,我无法将table2加入我必须使用子查询的所有记录

2 个答案:

答案 0 :(得分:1)

希望这会让你朝着正确的方向前进......

select sum(a.salary)
from table1 a
left join table2 b on a.person = b.person and b.salary_type = "something"
where a.id > 10
;

答案 1 :(得分:1)

我假设,你的工资没有正确总结(你得到的比你想象的要多)。这是因为LEFT JOIN将为b中没有匹配的行留下NULL。 对于这个SQL:

SELECT a.*, b.*
FROM   (select * from (SELECT 123   AS Salary,
               'Tom' AS person
        UNION
        SELECT 343   AS Salary,
               'Bob' AS person
        UNION
        SELECT 877   AS Salary,
               'Tom' AS person) as t where t.Salary > 123) a
       LEFT JOIN (SELECT *
                  FROM   (SELECT 'Tom' AS person,
                                 1     AS id
                          UNION
                          SELECT 'Bob' AS person,
                                 2     AS id) AS t
                  WHERE  t.id = 1) AS b
              ON a.person = b.person  

你将得到这个输出:

sql

所以INNER JOIN应该适合你。

SELECT SUM(SALARY) FROM (SELECT * FROM table1 WHERE id > 10) a
LEFT JOIN table2 b on a.person = b.person