SQL连接两个SELECT语句 - 相当简单

时间:2015-04-16 05:35:21

标签: mysql sql join

我正在尝试将两个查询结果合并到一个看起来像的输出中:

datetime |  BC  |  AC     
----------------------
sun      |  1.0 |  0.9

通过下面的MySQL调用(在MySQL中)。我可以正确地查询单个语句,但组合连接不起作用。有什么建议?谢谢!抱歉格式化。

SELECT z.datetime, (z.w_1 + z.w_2 + z.w_3) as 'BC', (b.w_1 + b.w_2 + b.w_3) as 'AC'  
 (FROM monitor_data a  
   WHERE mon_id = "site A"  
     AND datetime > "2015-04-02 04:30:00" 
     AND datetime < "2015-04-02 06:30:00") z

 JOIN (SELECT b.datetime, b.w_1, b.w_2, b.w_3      
   FROM monitor_data b 
     WHERE mon_id = "site B"  
       AND datetime> "2015-04-02 04:30:00" 
       AND datetime < "2015-04-02 06:30:00") y 
 ON y.datetime = z.datetime

2 个答案:

答案 0 :(得分:1)

你没有完全正确的语法。要连接两个派生表(z和y),您需要确保每个派生表都具有语法完整的SELECT语句。另外,请记住,第二个派生表现在别名为“y”,而不是b

SELECT z.datetime, (z.w_1 + z.w_2 + z.w_3) as BC, 
       (y.w_1 + y.w_2 + y.w_3) as AC
FROM 
(
   SELECT a.datetime, a.w_1, a.w_2, a.w_3
   FROM monitor_data a 
   WHERE mon_id = 'site A' 
    AND datetime > '2015-04-02 04:30:00' AND datetime < '2015-04-02 06:30:00'
) z
JOIN 
(
  SELECT b.datetime, b.w_1, b.w_2, b.w_3
  FROM monitor_data b 
  WHERE mon_id = 'site B' 
    AND datetime > '2015-04-02 04:30:00' AND datetime < '2015-04-02 06:30:00'
) y
ON y.datetime = z.datetime;

答案 1 :(得分:0)

试试这个..

SELECT z.datetime, (z.w_1 + z.w_2 + z.w_3) as 'BC', (y.w_1 + y.w_2 + y.w_3) as 'AC'
(select a.datetime, a.w_1,a.w_2,a.w_3,
 FROM   monitor_data a 
 WHERE  mon_id = "site A" 
    AND datetime > "2015-04-02 04:30:00" 
    AND datetime < "2015-04-02 06:30:00") z

JOIN (SELECT b.datetime, b.w_1, b.w_2, b.w_3
      FROM   monitor_data b 
      WHERE  mon_id = "site B" 
         AND datetime > "2015-04-02 04:30:00" 
         AND datetime < "2015-04-02 06:30:00") y

ON y.datetime = z.datetime