【问题标题】:SQL conditional INNER JOIN with two different tables具有两个不同表的 SQL 条件 INNER JOIN
【发布时间】:2023-03-17 23:16:02
【问题描述】:

我有一个应该首先执行的简化子查询:

(SELECT app.recordId, left(userid,1) userid, count(*)FROM
      app group by userid,recordId) y

根据此子查询的结果,如果userid='A' 我想与tableA 进行INNER JOIN,If userid='B',我想与tableB 进行INNER JOIN。

我还希望显示两个内部连接的结果。有没有办法让我可以在不重新执行子查询的情况下做到这一点以最小化执行时间?

【问题讨论】:

  • 子查询/派生表中的GROUP BY子句不正确。应该是group by left(userid,1),recordId。另外请澄清“我也希望出现两个内部连接的结果”是什么意思。
  • @PaxBin 试试FROM table t Left join TableA on t.userid ='A' Left join TableB on t.userid = 'B'
  • 请提供您的实际表结构、示例数据和预期输出。 stackoverflow.com/help/how-to-ask
  • @TT。 . . .一些数据库支持这种语法,尽管 OP 应该通过正确标记问题来清楚地了解正在使用的数据库。
  • @GordonLinoff 哦,好点子。我总是假设它是 TSQL ......呵呵 =)

标签: sql inner-join multiple-tables


【解决方案1】:

一种方法是使用left join 两次,可能与coalesce() 一起使用:

SELECT y.*, COALESCE(a.col1, b.col1) as col1
FROM (SELECT app.recordId, left(userid, 1) as userid, count(*) as cnt
      FROM app
      GROUP BY recordId, left(userid, 1)
     ) y LEFT JOIN
     tableA a
     ON y.userId = 'A' and . . . LEFT JOIN
     tableB b
     ON y.userId = 'B' and . . .
WHERE y.userId IN ('A', 'B');

. . . 是用于附加连接条件的空间,问题未指定。

编辑:

如果您想过滤掉不匹配的行(也就是“内连接”方法):

WHERE y.userId IN ('A', 'B') and not (a.col is null and b.col is null)

其中a.colb.col 是用于join 条件的两列。

【讨论】:

  • WHERE 子句可用于通过断言发生了正确的连接来使这些连接更加“内部”,例如(y.userId = 'A' and a.nonnullablecolumn IS NOT NULL) or (y.userId='B' and b.nonnullablecolumn IS NOT NULL)
  • 左连接方法可行,但我仍然会得到两个表上都没有匹配的结果,内部连接不会显示
  • @gordon-linoff 也许最好的方法是将子查询的结果存储在临时表中,并将其用于两个连接以及两个查询之间的联合
【解决方案2】:

您没有说您希望如何处理表 A 和 B 中的列。我们也不知道这些表是如何相关的。所以我只能给你一个例子。

假设您想要来自表 A 或 B 的描述:

select agg.userid, a_and_b.description, agg.recordid, agg.rec_count
from 
(
  select left(userid,1) as userid, recordid, count(*) as rec_count
  from app
  group by left(userid,1), recordid
) agg
join
(
  select 'A' as userid, recordid, description from a
  union all
  select 'B' as userid, recordid, description from b
) a_and_b on a_and_b.userid = agg.userid and a_and_b.recordid = agg.recordid;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    相关资源
    最近更新 更多