Could someone explain to me what this line of PHP/SQL is trying to accomplish
I was asked to fix a problem with the website of a customer, and I think this line is at least partly responsible for the error:
$SQL="select 'SC' ||substr(10000+max(to_number(secondid, '99G999D9S'))+1,2,4) from table";
I can't quite tell what this line above is trying to accomplish, whether it's just a bad piece of code that wasn't written correctly or something important and well thought out. I know that substr is a PHP function, and yet, it's in the double quotes开发者_如何转开发, so it's part of the query, and I also know that max and to_number are postgresql functions. I have no idea what SC is, it isn't a field in the table. If I run this query by itself:
SELECT 'SC' FROM table;
I get a ?column?(of unknown type), and the number of rows is one greater than the number of rows in the table (or the same if you include the empty row at the end of each table). Each row simply states holds SC. What's the point of the || operator? If I recall correctly, that is an OR operator, so how does the query decide what it wants to select?
Sorry for the trouble, thanks for your time.
Working in-side out:
The original statement:
$SQL="select 'SC' ||substr(10000+max(to_number(secondid, '99G999D9S'))+1,2,4) from table";
The components:
'99G999D9S'
A format specificer: 2 digits + group separator + 3 digits + decimal point + 1 digit + sign.
to_number(secondid, '99G999D9S')
Convert the secondid field to a number using the above format.
max(...)
Standard SQL max function.
10000+max(...)+1
Add 10,001 to the results of max.
substr(...,2,4)
Extract 4 characters from the results of the previous, starting at char position 2.
SC || substr(...)
Concatenate the string from above with SC
.
The query is taking the value of field secondid
, converts it to numerical, using 99G999D9S
, then finds the max of these values across the table, add 10000 and 1 to it; converts the result to string, takes the substring 4-char long starting from the second character; finally appends it string 'SC' and returns to you. For a table where secondid
column is defined and is formatted accordingly, you will get exactly 1 result back. If this column is not defined or is formatted differently, you'll get an error.
||
operator is the concatenation in SQL.
精彩评论