views:

40

answers:

3

Hello. 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

+1  A: 

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

mopoke
Your are right. Honestly, mine is not a requirement of PRIMARY key but that of a UNIQUE key. I am now concatenating three keys and making a UNIQUE key out of it.
Kabeer
+1  A: 

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?

Paul Creasey
Paul, inspired from your thought, I am now concatenating three keys and making a UNIQUE key out of it. Honestly, mine is not a requirement of PRIMARY key but that of a UNIQUE key. Thanks.
Kabeer
A: 

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)

Rob Farley