Перейти к содержимому

Phpmyadmin как удалить связь

  • автор:

Relations¶

phpMyAdmin allows relationships (similar to foreign keys) using MySQL-native (InnoDB) methods when available and falling back on special phpMyAdmin-only features when needed. There are two ways of editing these relations, with the relation view and the drag-and-drop designer – both of which are explained on this page.

You need to have configured the phpMyAdmin configuration storage for using phpMyAdmin only relations.

Technical info¶

Currently the only MySQL table type that natively supports relationships is InnoDB. When using an InnoDB table, phpMyAdmin will create real InnoDB relations which will be enforced by MySQL no matter which application accesses the database. In the case of any other table type, phpMyAdmin enforces the relations internally and those relations are not applied to any other application.

Relation view¶

In order to get it working, you first have to properly create the [[pmadb|pmadb]]. Once that is setup, select a table’s “Structure” page. Below the table definition, a link called “Relation view” is shown. If you click that link, a page will be shown that offers you to create a link to another table for any (most) fields. Only PRIMARY KEYS are shown there, so if the field you are referring to is not shown, you most likely are doing something wrong. The drop-down at the bottom is the field which will be used as the name for a record.

Relation view example¶

_images/pma-relations-relation-view-link.png _images/pma-relations-relation-link.png

Let’s say you have categories and links and one category can contain several links. Your table structure would be something like this:

  • category.category_id (must be unique)
  • category.name
  • link.link_id
  • link.category_id
  • link.uri .

Open the relation view (below the table structure) page for the link table and for category_id field, you select category.category_id as master record.

If you now browse the link table, the category_id field will be a clickable hyperlink to the proper category record. But all you see is just the category_id , not the name of the category.

_images/pma-relations-relation-name.png

To fix this, open the relation view of the category table and in the drop down at the bottom, select “name”. If you now browse the link table again and hover the mouse over the category_id hyperlink, the value from the related category will be shown as tooltip.

_images/pma-relations-links.png

Designer¶

The Designer feature is a graphical way of creating, editing, and displaying phpMyAdmin relations. These relations are compatible with those created in phpMyAdmin’s relation view.

To use this feature, you need a properly configured phpMyAdmin configuration storage and must have the $cfg[‘Servers’][$i][‘table_coords’] configured.

To use the designer, select a database’s structure page, then look for the Designer tab.

To export the view into PDF, you have to create PDF pages first. The Designer creates the layout, how the tables shall be displayed. To finally export the view, you have to create this with a PDF page and select your layout, which you have created with the designer.

Удаление связанных записей в MySQL одним запросом

В MySQL есть возможность удалять связанные данные через внешние ключи (foreign key). Но это возможно только для некоторых движков БД (например, InnoDB) и в том случае, если для ключей задано ограничение ON DELETE CASCADE . В противном случае придется удалять записи вручную. Как раз об этом и пойдет речь в этой заметке.

Допустим у нас есть 2 таблицы: таблица товаров и изображений товаров:

  • product (id, name, price, description, active)
  • product_image (id, product_id, src, alt)

И нам необходимо удалить все неактивные товары вместе с изображениями. Для этого придется написать DELETE запрос с JOIN -ом и указать таблицы в которых необходимо произвести удаление данных.

Запрос, который решит указанную выше задачу, будет выглядеть следующим образом:

Если архитектура базы подразумевает связь еще через таблицу, то добавляем еще один джоин. Запрос удаляет только таблицы указанные после DELETE , остальные таблицы, которые участвуют в запросе, останутся без изменений.

MySQL Removing Some Foreign keys

I have a table whose primary key is used in several other tables and has several foreign keys to other tables.

The problem is that when I’m trying to drop one of the foreign key columns (ie locationIDX) it gives me an error.

«ERROR 1025 (HY000): Error on rename»

How can I drop the column in the assignment table above without getting this error?

Sankar's user avatar

11 Answers 11

As explained here, seems the foreign key constraint has to be dropped by constraint name and not the index name.

informatik01's user avatar

The foreign keys are there to ensure data integrity, so you can’t drop a column as long as it’s part of a foreign key. You need to drop the key first.

I would think the following query would do it:

zombat's user avatar

As everyone said above, you can easily delete a FK. However, I just noticed that it can be necessary to drop the KEY itself at some point. If you have any error message to create another index like the last one, I mean with the same name, it would be useful dropping everything related to that index.

Karla Danitza Duran Memijes's user avatar

Check what’s the CONSTRAINT name and the FOREIGN KEY name:

Remove both the CONSTRAINT name and the FOREIGN KEY name:

Hope this helps!

Hey I followed some sequence above, and found some solution.

You will get FK Constrain Name like

Now you need to remove this constraints. by alter table commantd

Then drop the table column,

Here’s a way to drop foreign key constraint, it will work. ALTER TABLE location . location_id DROP FOREIGN KEY location_ibfk_1 ;

Rock King Kirant's user avatar

You usually get this error if your tables use the InnoDB engine. In that case you would have to drop the foreign key, and then do the alter table and drop the column.

But the tricky part is that you can’t drop the foreign key using the column name, but instead you would have to find the name used to index it. To find that, issue the following select:

SHOW CREATE TABLE region; This should show you a row ,at left upper corner click the +option ,the click the full text raio button then click the go .there you will get the name of the index, something like this:

CONSTRAINT region_ibfk_1 FOREIGN KEY (country_id) REFERENCES country (id) ON DELETE NO ACTION ON UPDATE NO ACTION Now simply issue an:

alter table region drop foreign key region_ibfk_1;

more simply just type:- alter table TableName drop foreign key TableName_ibfk_1;

remember the only thing is to add _ibfk_1 after your tablename to make like this:- TableName_ibfk_1

Создание связей между таблицами с помощью phpmyadmin

В этой заметке мы научимся создавать связи между таблицами в базе данных MySQL с помощью phpmyadmin. Если по какой-то причине вы не желаете использовать phpmyadmin, смотрите приведенные ниже SQL-запросы.

Почему же связи удобно держать в самой базе данных? Ведь эту задачу обычно решает так и само приложение? Все дело в ограничениях и действиях при изменении, которые можно наложить на связи.

Например, можно запретить удалять категорию, если с ней связана хотя б одна заметка. Или удалить все заметки, если удалена категория. Или установить NULL в связующее поле. В любом случае, с помощью связей повышается отказоустойчивость и надежность приложения.

Для начала, движок таблиц должен быть InnoDB . Только он поддерживает внешние ключи ( foreign key ). Если у вас таблицы MyISAM , почитайте как их конвертировать в InnoDB .

Для того, чтобы связать таблицы по полям, необходимо сначала добавить в индекс связываемые поля:

В phpmyadmin выбираем таблицу, выбираем режим структуры, выделяем поле, для которого будем делать внешнюю связь и кликаем Индекс.

index MySQLОбратите внимание на разницу между "Индекс" и "Уникальный". Уникальный индекс можно использовать, например, до поля id, то есть там, где значения не повторяются.

Это же действие можно сделать с помощью SQL-запроса:

Аналогично добавляем индекс (только в моем случае теперь уже уникальный или первичный) для таблицы, на которую ссылаемся, для поля id. Поскольку поле id у меня идентификатор, для него делаем первичный ключ. Уникальный ключ мог бы понадобится для других уникальных полей.

index MySQL С помощью SQL-запроса:

Теперь осталось только связать таблицы. Для этого кликаем внизу на пункт Связи:

phpmyadmin MySQL connections

Теперь для доступных полей (а доступны только проиндексированные поля) выбираем связь с внешними таблицами и действия при изменении записей в таблицах:

Connections with MySQL tablesЧерез SQL-запрос:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Luxury Car Rental in Miami | Reserve a Premium Vehicle with RealCar