2014-09-12 118 views
1

例子:SQL连接表中选择记录

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

我想加盟表2只记录到(SELECT * FROM table1 WHERE id > 10)记录,我的例子是不正确的。

table1包含100mln记录,我不能参加table2所有记录我必须使用子查询

+0

哪个表是'salary'列中的? – 2014-09-12 12:04:59

+0

它是table1列 – Wizard 2014-09-12 12:05:32

+0

@TomMac它是onlny示例我neet有'salary_type'从table2并添加条件来只计算一些aslary类型。 – Wizard 2014-09-12 12:12:00

回答

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 
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 
;