MySQL如何创建与查询参数一起使用的视图

问题描述 投票:1回答:1

使用MySQL 8

我有cuenta_contable表(它是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;

并按预期工作,它返回8行。

观察它使用:

  • cc.code = '32'
  • cc2.code = '32'

想让这种观点更加生动[[动态我需要将这两个32替换为?

    cc.code = ?
  • cc2.code = ?
  • 执行以下操作:

      SELECT * FROM cuenta_contable_union_view_with_code WHERE cc.code='30' and cc2.code='30'
  • SELECT * FROM cuenta_contable_union_view_with_code WHERE cc.code='40' and cc2.code='40'
  • 很难,如果我在视图声明中使用?,那么会发生:

    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;

    因此使用:

      SELECT * FROM cuenta_contable_union_view_with_code;
  • 有效,但会返回所有内容-8个中的更多内容>>

      SELECT * FROM cuenta_contable_union_view_with_code WHERE code = '32';
  • 观察WHERE部分。它仅返回

    1

  • 行,而不返回8“静态”第一版的显示方式。因此如何解决?

    我最糟糕的情况是创建许多“静态”视图,但它很冗长,不太实用

    使用MySQL 8,我拥有cuenta_contable表(它是自引用的)和以下视图:CREATE VIEW cuenta_contable_union_view_with_code_32 AS(SELECT cc.code,cc.description ...

    mysql sql sql-view
    1个回答
    1
    投票
    can用WHERE子句等过滤它们。
    © www.soinside.com 2019 - 2024. All rights reserved.