联接两个查询结果(具有WHERE和IN子句+子查询)

时间:2018-07-14 08:26:52

标签: mysql join

尝试重新创建以下问题(不包括IN子句和子查询):

/* this is query 1 */    
Select A.column_1,B.keyValue from table1 as A, table2 as B where
A.someColumn = B.someColumn and B.someotherColumn = 10

/* query 1 gives */
column1 | keyValue
_________________

data-A1 | key-1 
data-A2 | key-2
data-A3 | key-3

/* this is query 2 */
Select AVG(ratings) as ratings, C.keyValue from table3 as C, 
table4 as D where C.someColumn = D.someColumn and D.someotherColumn = 'abc'

/* query 2 gives */
ratings | keyValue
_________________

rating-1 | key-1 
rating-2 | key-2
rating-3 | key-3

/* this is the desired result */

column1 | ratings | keyValue
_________________

data-A1 | rating-1 | key-1 
data-A2 | rating-2 | key-2
data-A3 | rating-3 | key-3

我用Google搜索它,发现mysql join是解决方案

SELECT table1.id, table2.column1, table1.column2 FROM table1 
INNER JOIN table2 ON table1.id = table2.id;

但是,这是一个非常基本的示例,仅包含两个表,我的第一个查询实际上包含5个表,第二个查询包含4个具有多个WHERE和IN子句+子查询的表。我无法通过复杂的查询来实现此JOIN逻辑。这是我尝试过的方法,但是在“ JOIN”关键字之后给了我一个错误:

Select * from (Select A.column_1,B.keyValue from table1 as A, table2 as B 
where A.someColumn = B.someColumn and B.someotherColumn = 10) as first
JOIN
Select * from (Select AVG(ratings) as ratings, C.keyValue from table3 as C, 
table4 as D where C.someColumn = D.someColumn and D.someotherColumn = 'abc')
as second ON first.keyValue = second.keyValue;

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

我不知道您的4个表的结构,但是基于您的2个查询,您可以执行以下操作:

select
   X.column_1,
   Y.ratings,
   X.key_value 
From
   (
      Select
         A.column_1,
         B.keyValue 
      from
         table1 as A,
         table2 as B 
      where
         A.someColumn = B.someColumn 
         and B.someotherColumn = 10 
   )
   X 
   INNER JOIN
      (
         Select
            AVG(ratings) as ratings,
            C.keyValue 
         from
            table3 as C,
            table4 as D 
         where
            C.someColumn = D.someColumn 
            and D.someotherColumn = 'abc' 
      )
      Y 
      on X.keyvalue = Y.keyvalue;

X和Y称为派生表。

P.S:如果我们知道基础表的结构,示例数据以及您要实现的目标,则可能会创建更好的查询。根据这些信息,这是我能给您的最佳答案。

相关问题