Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Update Query using a left join

Tags:

Table Schema

Table Name: file_manager_folder

Rows: id , parentId, name

My query simulates moving a folder into another folder and accepts an array using IN(?).

I want my update to only 'move' a folder if there is not already a folder with the same parentId and name. The kind of behaviour you would expect under any normal file system.

So for example:

UPDATE file_manager_folder set parentId = 54 where id IN( '1','2',3')  

Would be a query which doesn't check anything about the parentId and name... But how can I get the left join to work.

Here is one I tried.. which totally doesn't work.

SELECT * FROM      file_manager_folders as a LEFT JOIN file_manager_folders as b on a.id = b.id  WHERE b.id IS NOT NULL and a.id IN("1","2","3") and a.parentId = 54 

UPDATE table1 LEFT JOIN table2 SET t1.x = t2.y ON condition WHERE conditions

like image 578
Layke Avatar asked Jul 14 '10 16:07

Layke


People also ask

Can we use left join in update query?

SQL Server UPDATE JOIN syntax To query data from related tables, you often use the join clauses, either inner join or left join. In SQL Server, you can use these join clauses in the UPDATE statement to perform a cross-table update.

Can we use join in update query in MySQL?

MySQL UPDATE JOIN syntax In MySQL, you can use the JOIN clauses in the UPDATE statement to perform the cross-table update.

Can we use update query in joins?

The most easiest and common way is to use join clause in the update statement and use multiple tables in the update statement. Here we can see that using join clause in update statement. We have merged two tables by the use of join clause.

Are left joins allowed in MySQL?

Introduction to MySQL LEFT JOIN clauseThe LEFT JOIN allows you to query data from two or more tables. Similar to the INNER JOIN clause, the LEFT JOIN is an optional clause of the SELECT statement, which appears immediately after the FROM clause.


2 Answers

So you want to move folders only if a folder of the same name under the target parent folder does not exist:

UPDATE file_manager_folder f1 LEFT OUTER JOIN file_manager_folder f2      ON f1.name = f2.name AND f2.parentId = 54 SET f1.parentId = 54  WHERE f2.name IS NULL AND f1.id IN (1,2,3); 

The join condition searches for a folder with the same name under the target parent. The WHERE clause tests that no such folder exists (f2.name is null only if the outer join finds no match).

like image 109
Bill Karwin Avatar answered Jan 01 '23 20:01

Bill Karwin


I think this should be solved using a unique constraint/index on the parentid and name columns. Otherwise, anyone with INSERT/UPDATE access to the table can circumvent your business rule.

CREATE UNIQUE INDEX blah_uk ON FILE_MANAGER_FOLDER(parentId, name) USING BTREE 
like image 27
OMG Ponies Avatar answered Jan 01 '23 21:01

OMG Ponies