Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete from table if the id doesn't exists in another table

I want to delete the id's from types that can't be found in types_photos but I don't know how I can accomplish this. id_type in types_photos are the same as id in types. Here's how the table's structure looks like:

CREATE TABLE IF NOT EXISTS `types` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `id_user_added` int(11) DEFAULT '0',
  `id_user_edited` int(11) DEFAULT '0',
  `data_name` text NOT NULL,
  `data_name_seo` text NOT NULL,
  `data_type` enum('tag','equipment','search') NOT NULL,
  `datetime_added` datetime NOT NULL,
  `datetime_edited` datetime NOT NULL,
  `ipaddress_added` text NOT NULL,
  `ipaddress_edited` text NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`)
)

CREATE TABLE IF NOT EXISTS `types_photos` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `id_user_added` int(11) DEFAULT '0',
  `id_user_edited` int(11) DEFAULT '0',
  `id_type` int(11) DEFAULT '0',
  `id_photo` int(11) DEFAULT '0',
  `datetime_added` datetime NOT NULL,
  `datetime_edited` datetime NOT NULL,
  `ipaddress_added` text NOT NULL,
  `ipaddress_edited` text NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`)
)

So, my question is; how can I delete all id's from types that can't be found in types_photos?

like image 925
Airikr Avatar asked Oct 20 '13 20:10

Airikr


People also ask

Can we delete a row from a table based on another table?

Deleting rows based on another table. Sometimes we need to delete rows based on another table. This table might exist in the same database or not. We can use the table lookup method or SQL join to delete these rows.

How do you know if data exists in one table and not in another?

To test whether a row exists in a MySQL table or not, use exists condition. The exists condition can be used with subquery. It returns true when row exists in the table, otherwise false is returned. True is represented in the form of 1 and false is represented as 0.

What would happen if you executed a delete statement against a table with no WHERE clause?

If you will not provide where clause with delete statement, then whole table data will be deleted. Use this very carefully to avoid any unwanted data loss. Delete From Customer; In the syntax above the deletion happens without any condition and will delete all the records of the table.


1 Answers

DELETE FROM types 
WHERE id NOT IN (
  SELECT ID FROM types_photos
)
like image 190
Akash Avatar answered Oct 15 '22 23:10

Akash