How can I have a primary key in a VIEW (a key that doesn't depend on source tables)

99封情书 提交于 2019-12-06 03:43:16

you could use various methods to insert a unique ID to the view data, such as:

SELECT @rownum:=@rownum+1 as id, mytable.*
FROM (SELECT @rownum:=0) r, mytable;

However this is not a primary key, it is not consistant and will change when the data changes.

What exactly do you need a key for?

The highest voted answer using

SELECT @rownum:=@rownum+1 as id, mytable.*
FROM (SELECT @rownum:=0) r, mytable;

Is incorrect - you cannot create a view in mysql that uses a sub-select in the FROM. You're only option is to treat a set of columns as a composite key.

Views don't have primary keys or indexes - the mysql engine will use the indexes and keys defined on the base table(s).

A view is just a stored sub-query. The idea of a PK is irrelevant.

...unless you need an indexed view, in which case you need a Clustered Index on the view (but still not necessarily a Primary Key)

(although, I'm talking SQL Server... I'm not sure how this translates to MySQL)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!