1

我越来越喜欢CREATE VIEW. 例如,它允许我拥有全局值和特定值,COALESCE(post.publish, profile.publish)这样如果publishNULL,则获取全局值。

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

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

并且仅post_infoSELECT某些情况下使用,或者:

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_info的价值?postSELECT

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

4

1 回答 1

0

It really depends on how you will use the views. It should be worth mentioning that there are two methods MySQL can process a query that refers to a view, and the method used depends on the view declaration's ALGORITHM clause.

For the lack of a better phrasing, I will reproduce 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.

The MERGE algorithm usually allows faster processing of the final query, however there are many cases where MySQL is unable to use it (see the linked manual page for more details).

So the answer is: if your view is not defined with ALGORITHM = TEMPTABLE and if the wrapping query does not prevent the use of the MERGE algorithm, the version with SELECT *, and without an extra JOIN, is better.

Otherwise, if MERGE is not used, the second solution could be better.

As a side note, to adress the use case you mention, a better option would be to have your application layer fill the post.publish with the value in profile.publish at insertion time, and get rid of the JOIN as well as the view. Alternatively, the same effect can be achieved by placing a suitable trigger on the table.

于 2013-06-27T10:07:31.153 回答