MySQL View的SELECT在FROM子句中包含一个子查询...帮助重写吗?

时间:2018-08-10 12:17:32

标签: mysql

我正在构建一个Web应用程序,该应用程序需要从单个视图中引用数据。

我知道在create或replace视图的子查询中不能有from子句,但是我只能提出该查询的一个版本来返回我需要的结果。

经过数小时的拖曳,我无法提出任何解决方案。 有没有比我更聪明的人可以以一种可以在单个视图中返回所有数据的方式重新构造该查询呢? 这是查询...

CREATE
OR REPLACE VIEW in_stock_levels AS
SELECT
  *,
  `in_stock` - `maximum_stock` AS levels
FROM(
    SELECT
      stock_levels.id AS id,
      stock_levels.part_number AS part_number,
      stock_levels.minimum_stock AS minimum_stock,
      stock_levels.maximum_stock AS maximum_stock,
      (
        SELECT
          COUNT(*)
        FROM
          automatic_transmission_jobs
        WHERE
          part_number = stock_levels.part_number
          AND test_result != "Not Tested"
          AND status != "pwa"
      ) AS in_stock
    FROM
      stock_levels
  ) AS check_stock

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

在没有有关架构的更多信息的情况下,但是基于您发布的内容,以下查询应适用于您的CREATE或REPLACE VIEW ...

self._w

您是否使用phpMyAdmin或MySQLWorkbench设计和测试查询?

答案 1 :(得分:0)

以这种方式进行是可行的,我知道这不是最有效的,

CREATE
OR REPLACE VIEW in_stock_levels AS
SELECT
      stock_levels.id AS id,
      stock_levels.part_number AS part_number,
      stock_levels.minimum_stock AS minimum_stock,
      stock_levels.maximum_stock AS maximum_stock,
      (
        SELECT
          COUNT(*)
        FROM
          automatic_transmission_jobs
        WHERE
          part_number = stock_levels.part_number
          AND test_result != "Not Tested"
          AND status != "pwa"
      ) AS in_stock,
      (
        SELECT
          COUNT(*)
        FROM
          automatic_transmission_jobs
        WHERE
          part_number = stock_levels.part_number
          AND test_result != "Not Tested"
          AND status != "pwa"
      ) - stock_levels.maximum_stock AS stock_level
    FROM
      stock_levels
 

感谢您对Ingo的所有帮助:)