Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UPDATE with ORDER BY and LIMIT not working in MYSQL

Tags:

mysql

limit

I am new to MYSQL, and unable to resolve or even with so many answers on this forum, unable to identiy the error in this statement. I am using MYSQL database.

I have 2 tables: Ratemaster and rates, in which a customer can have 1 product with different rates. Because of this, there is a duplication of customer and product fields, only the rate field changes. Now Table Ratemaster has all the fields : id, Customer code, Product, Rate, user whereas Table Rates has only: id, cust code, Rate, user. - user field is for checking session_user.

Now Table Ratemaster has 3 records with all field values being same except Rate field empty. Table Rates has different rates. I want to have all rates to be updated in Ratemaster from Rates table. I am unable to do this with UPDATE and LIMIT mysql command, it is giving error as:

Incorrect usage of UPDATE and LIMIT

UPDATE Ratemaster, Rates 
SET Ratemaster.Rate=Rates.Rate 
WHERE Ratemaster.user=Rates.user 
LIMIT 1
like image 247
user1114409 Avatar asked Jan 31 '12 13:01

user1114409


People also ask

Can we use ORDER BY in update query in MySQL?

You Can Use ORDER BY And LIMIT Within UPDATE And DELETE Statements In MySQL 5.6. 37.

Can we use LIMIT with ORDER BY in MySQL?

If you combine LIMIT row_count with ORDER BY , MySQL stops sorting as soon as it has found the first row_count rows of the sorted result, rather than sorting the entire result. If ordering is done by using an index, this is very fast.

Does MySQL allow the use of ORDER BY and LIMIT in the same query?

In MySQL, the LIMIT clause is used with the SELECT statement to restrict the number of rows in the result set. The Limit Clause accepts one or two arguments that are offset and count. The value of both the parameters can be zero or positive integers.

Can you use LIMIT with update SQL?

Yes, it is possible to use UPDATE query with LIMIT in MySQL.


1 Answers

Usually you can use LIMIT and ORDER in your UPDATE statements, but in your case not, as written in the MySQL Documentation 12.2.10. UPDATE Syntax:

For the multiple-table syntax, UPDATE updates rows in each table named in table_references that satisfy the conditions. In this case, ORDER BY and LIMIT cannot be used.

Try the following:

UPDATE Ratemaster
SET Ratemaster.Rate =
(
    SELECT Rates.Rate
    FROM Rates
    WHERE Ratemaster.user = Rates.user
    ORDER BY Rates.id
    LIMIT 1
)
like image 162
Sascha Galley Avatar answered Oct 14 '22 11:10

Sascha Galley