在SQL

时间:2018-02-20 18:29:25

标签: mysql sql join

我不确定我选择了正确的标题,但我尽力解释我要做的事情。我正在学习连接,我有两个表,我试图以某种方式组合,但它们都有WHERE子句。

我开始时分别构建两个SELECT语句。这是我表中的第一个:" shipping_zones"

SELECT MIN(cal_zone) AS output_zone
  FROM (
    SELECT carrier, dest_zip, origin_zip, zone, MIN(zone) OVER(PARTITION BY carrier) as cal_zone
      FROM shipping_zones z
        WHERE (origin_zip = 402 OR origin_zip = 950) AND dest_zip = 015
      ) as t
WHERE zone=cal_zone;

返回:

+-------------+
| output_zone |
+-------------+
| 5           |
+-------------+

我的第二张表是:" shipping_prices"我的疑问是:

SELECT carrier, speed, zone, min_price
FROM (SELECT carrier, zone, speed, price, MIN(price) OVER(PARTITION BY speed) as min_price
      FROM shipping_prices
      WHERE total_wt = 66 and zone = 6
     ) t
WHERE price=min_price
ORDER BY speed DESC;

结果是:

+---------+-------+------+-----------+
| carrier | speed | zone | min_price |
+---------+-------+------+-----------+
| fedex   | slow  | 6    | 45.66     |
| usps    | med   | 6    | 96.05     |
| usps    | fast  | 6    | 347.15    |
+---------+-------+------+-----------+

我想做的是"传递"第一个查询中 output_zone 的值为"参数"进入第二个查询。我把引用词放在引号中,因为我不确定这是正确的词。

我最好在SQL中完成此操作是使用正确的连接吗?我理解连接的基本语法但由于我在两个(WHERE,MIN,ORDER BY等)中使用的子句而有点丢失

编辑:这个数据是用Impala查询的,在用HIVE导入HDFS之前在MySQL中创建。

EDIT2:我还应该提到" shipping_prices" table已经有一个名为" zone"的字段。所以我想我不会"传递"它可以使用第一个查询输出中的值来在" shipping_prices"中找到合适的元组。表

任何帮助或提示都将不胜感激。

1 个答案:

答案 0 :(得分:1)

您只需将第一个查询放入一个zone in (first_query)语句即可替换zone=6

代码如下所示:

SELECT carrier, speed, zone, min_price
FROM (SELECT carrier, zone, speed, price, MIN(price) OVER(PARTITION BY speed) as min_price
      FROM shipping_prices
      WHERE total_wt = 66 
      and zone in (
        SELECT MIN(cal_zone) AS output_zone
          FROM (
            SELECT carrier, dest_zip, origin_zip, zone, MIN(zone) OVER(PARTITION BY carrier) as cal_zone
              FROM shipping_zones z
                WHERE (origin_zip = 402 OR origin_zip = 950) AND dest_zip = 015
              ) as t
        WHERE zone=cal_zone;
      )
     ) t
WHERE price=min_price
ORDER BY speed DESC;

看来你正在使用Mysql 8.0(开发版),Mysql Engine会进行合理的查询优化,这很可能会将 IN JOIN 查询重写为相同的计划。请查看此网址以获取详细信息Convert IN to JOIN