简体   繁体   中英

MySQL - creating a unique column on a View

I want to edit the data held in a view on MySQL. I hadn't realised you could do this but according to this some views are editable.

https://dev.mysql.com/doc/refman/8.0/en/view-updatability.html

I've just checked the INFORMATION_SCHEMA.VIEWS table and the IS_UPDATEABLE flag is set to Yes for the view in question (view_company) so it looks like the view is updateable.

However when I try to edit the view using phpmyadmin I get the error:

#1288 - The target table view_company of the UPDATE is not updatable

I noticed that phpmyadmin is displaying the following message for view_company.

Current selection does not contain a unique column. Grid edit, Edit, Copy and Delete features may result in undesired behavior.

I am wondering if this could be the source of the problem but don't know how to set a column in the view to be unique when creating the view. The view is a very simple view so should meet the editability requirements detailed in the above link. The script used to create the view is below. The column company.PRIMARYKEY is the primary key from the company table so will be unique and could be set to be the unique column in the view.

CREATE VIEW view_company
AS
SELECT 
company.PRIMARYKEY AS COMPANYPK,
company.NAME,
company.ADDRESS1,
company.ADDRESS2,
company.ADDRESS3,
company.CITY,
company.PHONE,
company.WEBSITE,
country.NAME AS COUNTRY
FROM company
LEFT JOIN country ON company.COUNTRYFK = country.PRIMARYKEY
ORDER BY company.NAME ASC

To be able to update a table column via a view, you should include in the view the primary key (or a unique key) for the table whose column you are trying to update. In your case, since you are trying to update a column within the country table, you should include its primary key in the view, which I assume is country.PRIMARYKEY :

CREATE VIEW view_company
AS
SELECT 
company.PRIMARYKEY AS COMPANYPK,
company.NAME,
company.ADDRESS1,
company.ADDRESS2,
company.ADDRESS3,
company.CITY,
company.PHONE,
company.WEBSITE,
country.PRIMARYKEY AS COUNTRYPK, /* this is the addition you need */
country.NAME AS COUNTRY
FROM company
LEFT JOIN country ON company.COUNTRYFK = country.PRIMARYKEY
ORDER BY company.NAME ASC

I understand what is happening. Left Join is short for Left Outer Join You can't update views that are created with an Outer Join

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM