【问题标题】:SQL join table to selected recordsSQL 将表连接到选定的记录
【发布时间】:2014-09-12 11:29:53
【问题描述】:

例子:

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 包含 1 亿条记录,我无法将 table2 加入必须使用子查询的所有记录

【问题讨论】:

  • salary 列在哪个表中?
  • @TomMac 这是唯一的例子,我需要 salary_type FROM table2 并添加条件以仅计算一些 aslary 类型。
  • (1) 为什么你的例子不正确? (2) 为什么不能对所有记录使用table2? (3) 为什么一定要用子查询?
  • 因为我有这么多记录。

标签: mysql sql subquery left-join


【解决方案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  

你会得到这个输出:

所以INNER JOIN 应该适合你。

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

【讨论】:

    【解决方案2】:

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

    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
    ;
    

    【讨论】:

      猜你喜欢
      • 2010-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多