Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this SQL query do? Please explain

Tags:

sql

What means this query?

@numberx = @numberx -1
UPDATE  th
SET     @numberX= numberY= @numberX + 1
FROM    Table1 th
INNER JOIN Table2 td ON th.Id = td.idth
WHERE   td.anything = @anything

At line 3, what is this "double equality"? And what is this "from" and "inner" on an UPDATE?

like image 745
user1006743 Avatar asked Dec 19 '12 14:12

user1006743


People also ask

What is query explain in SQL?

The EXPLAIN keyword is used throughout various SQL databases and provides information about how your SQL database executes a query. In MySQL, EXPLAIN can be used in front of a query beginning with SELECT , INSERT , DELETE , REPLACE , and UPDATE .

What does mean this symbol '@' in SQL?

The @CustID means it's a parameter that you will supply a value for later in your code. This is the best way of protecting against SQL injection. Create your query using parameters, rather than concatenating strings and variables.

What is a query explain?

A query can either be a request for data results from your database or for action on the data, or for both. A query can give you an answer to a simple question, perform calculations, combine data from different tables, add, change, or delete data from a database.


1 Answers

It's a multiple table update for assigning consecutive numbers to each row in Table1 where the corresponding row in Table2 has a specific value for the column anything.

For each matching row it sets the column numberY to the value of @numberX + 1. It also reassigns that value back to @numberX, which causes @numberX to be incremented for each row.

This is known as a "quirky update". It is an undocumented and not guaranteed approach to generate running totals. In 2012 SUM() OVER (ORDER BY ...) should be used instead.

like image 103
Mark Byers Avatar answered Sep 28 '22 08:09

Mark Byers