gpt4 book ai didi

mysql - 在 View 中使用 select * 是否安全?

转载 作者:行者123 更新时间:2023-11-30 23:16:45 25 4
gpt4 key购买 nike

我越来越喜欢 CREATE VIEW 的实用性。例如,它允许我通过 COALESCE(post.publish, profile.publish) 获得全局值和特定值,这样如果 publishNULL,取而代之的是获取全局值。

从性能和逻辑的角度来看,我有点好奇的部分是我应该如何将它与现有表格一起使用。假设我有一张 table :

CREATE TABLE post (
id INT,
profile_id INT,
name VARCHAR,
publish ENUM('TRUE', 'FALSE') NULL
)

CREATE VIEW 是否最好像这样运行:

CREATE VIEW post_info AS
SELECT post.*, COALESCE(post.publish, profile.publish) AS publish
FROM post
INNER JOIN profile
ON post.profile_id = profile.id

并且仅在 SELECT 情况下使用 post_info,或者:

CREATE VIEW post_info AS
SELECT post.id, COALESCE(post.publish, profile.publish) AS publish
FROM post
INNER JOIN profile
ON post.profile_id = profile.id

当需要额外值时,JOIN post_infoSELECT 中的 post

请分享您对此的见解和想法。我想听听您对每种解决方案的优点和缺点的意见。也可以是我没有提到的。

最佳答案

这实际上取决于您将如何使用 View 。值得一提的是,MySQL 有两种方法可以处理引用 View 的查询,使用的方法取决于 View 声明的 ALGORITHM。条款。

由于缺乏更好的措辞,我将重现the manual :

For [ALGORITHM =] MERGE, the text of a statement that refers to the view and the view definition are merged such that parts of the view definition replace corresponding parts of the statement.

For TEMPTABLE, the results from the view are retrieved into a temporary table, which then is used to execute the statement.

For UNDEFINED, MySQL chooses which algorithm to use.

MERGE算法通常允许更快地处理最终查询,但是在许多情况下 MySQL 无法使用它(有关更多详细信息,请参阅链接的手册页)。

所以答案是:如果你的 View 没有用 ALGORITHM = TEMPTABLE 定义 如果包装查询不阻止使用 MERGE算法,带有SELECT *的版本,并且没有额外的 JOIN , 更好。

否则,如果MERGE没有使用,第二种解决方案可能会更好。

作为旁注,为了解决您提到的用例,更好的选择是让您的应用程序层填充 post.publish值在 profile.publish 中在插入时,去掉 JOIN以及 View 。或者,可以通过在 table 上放置合适的触发器来实现相同的效果。

关于mysql - 在 View 中使用 select * 是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17339070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com