MySQL 如何创建视图以使用查询参数

MySQL how create a view to work with query parameters

MySQL 8一起工作

我有 cuenta_contable table(它是 Self-Referential)和以下 View:

CREATE VIEW cuenta_contable_union_view_with_code_32 AS
(
SELECT
    cc.code, cc.description
FROM
    cuenta_contable cc
WHERE
    cc.code = '32'
)
UNION
(
SELECT
    cc1.code,
    cc1.description
FROM
    cuenta_contable cc1
INNER JOIN
    cuenta_contable cc2
ON
    cc1.parent_cuenta_contable = cc2.id_cuenta_contable
WHERE
    cc2.code = '32'
)
ORDER BY
    code ASC;

按预期工作,它 returns 8 行。

观察它使用:

我觉得这个观点更动态我需要用?

替换这两个32

执行以下操作:

遗憾的是这是不可能的,如果我在视图声明中使用 ? 然后会发生:

SQL Error [1064] [42000]: You have an error in your SQL syntax; 
check the manual that corresponds to your MySQL server version 
for the right syntax to use near '?

我已阅读其他帖子,但正在使用 Stored Procedures。主要关于:

在这种情况下不是使用 Stored Procedures 的选项,因为存在将来更改数据库的选项或风险。

我试过(删除了两个 WHERE):

CREATE VIEW cuenta_contable_union_view_with_code AS
(
SELECT
    cc.code, cc.description
FROM
    cuenta_contable cc
)
UNION
(
SELECT
    cc1.code,
    cc1.description
FROM
    cuenta_contable cc1
INNER JOIN
    cuenta_contable cc2
ON
    cc1.parent_cuenta_contable = cc2.id_cuenta_contable
)
ORDER BY
    code ASC;

因此使用:

有效,但 return 一切 - 更多 8

观察WHERE部分。它 return 只是 1 行而不是 8 'static' 第一个版本。

那怎么解决呢?

我最糟糕的情况是创建许多 'static' 视图,但它很冗长而且不太实用

如您所知,SQL 视图不能有参数。但是您 可以 使用 WHERE 子句等过滤它们。

这是你的任务模式。

  CREATE VIEW something AS (
    SELECT item1, item2, item3, item4
      FROM ...
   );

然后你像这样使用那个视图

 SELECT item2, item3, item4 
   FROM something
  WHERE item1 = 'constant'

不要太担心性能;查询规划器很聪明地从视图中优化查询。在您的情况下,它可能看起来像这样。

CREATE VIEW cuenta_contable_union AS (
    SELECT cc.code, cc.description, cc.code selector_code
      FROM cuenta_contable cc
     UNION
    SELECT cc1.code, cc1.description, cc2.code selector_code
      FROM cuenta_contable cc1
      JOIN cuenta_contable cc2 
             ON cc1.parent_cuenta_contable = cc2.id_cuenta_contable
 );

然后要使用视图选择您想要的 32 值项目,请执行以下操作:

SELECT code, description
  FROM cuenta_contable_union
 WHERE selector_code = 32
 ORDER BY code ASC;

下次是

SELECT code, description
  FROM cuenta_contable_union
 WHERE selector_code IN (10, 20, 30)
 ORDER BY code ASC;

或您的应用程序需要的任何内容。

如果您的 table 很大,如果您使用 UNION ALL 代替 UNION,此视图可能会更快。