简体   繁体   English

具有两个不同表的SQL条件INNER JOIN

[英]SQL conditional INNER JOIN with two different tables

I have a following simplified sub-query that should be executed first: 我有以下简化的子查询,应首先执行:

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

Based on the result of this subquery, if userid='A' I would like to INNER JOIN with tableA , If userid='B' , I'd like to INNER JOIN with tableB . 根据此子查询的结果,如果userid='A'我想用tableA INNER JOIN, If userid='B'我想用tableB INNER JOIN。

I also want the result of both inner joins to appear. 我也希望两个内部联接的结果都出现。 Is there a way so that I can do this without re-executing the subquery to minimize the execution time? 有没有一种方法可以使我无需重新执行子查询来最大程度地减少执行时间?

One approach is to use left join twice, probably with coalesce() : 一种方法是两次使用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');

The . . . . . . . . . is space for additional join conditions, which the question does not specify. 是其他联接条件的空间,问题未指定。

EDIT: 编辑:

If you want to filter out rows that have no matches (ala an "inner join" approach): 如果要过滤出不匹配的行(一种“内部联接”方法):

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

where a.col and b.col are two columns used for the join condition. 其中a.colb.col是用于join条件的两列。

You didn't say how you want the columns from the tables A and B to be handled. 您没有说要如何处理表A和B中的列。 We also don't know how the tables are related. 我们也不知道这些表是如何关联的。 So all I can give you is an example. 所以我能给你的就是一个例子。

Let's say you want a description that either comes from table A or 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM