2014-09-12 114 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 
;