Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm creating a VIEW out of 3 TABLES. Each TABLE has it's primary key. However, in the VIEW in order to have a primary key, I'll have to use a composite primary key (combination of primary keys of 3 TABLES).

I would however like to add a column in the VIEW as a primary key that is created just for the purpose of the VIEW. As part of the VIEW definition, it should be UNIQUE(autoincrement since it would be mostly an INT). How can I achieve this?

I am using MySQL 5.1

like image 460
Kabeer Avatar asked Dec 09 '22 18:12

Kabeer


1 Answers

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.

like image 164
David Clifton Avatar answered Dec 28 '22 06:12

David Clifton