User variables for MySQL

Source: Internet
Author: User
mysql| variable I feel very sad, why see more people, say less people.
Is it too simple and dismissive? Or do you want to keep a small hand?

The problem of the proposed id=2131117
There is a table that reads as follows
ID Name
1 AAA
4 BBB
6 CCC
A1
A2
Num B1
What to do to get the following results
ID Name P
1 AAA 1
4 BBB 2
6 CCC 3
4 A1
A2 5
Num B1 6
And how do you do that?
Name P
AAA AAA
BBB Triple A BBB
CCC AAA Triple BBB CCC
A1 AAA BBB CCC A1
A2 AAA BBB CCC A1 A2
B1 AAA BBB CCC A1 A2 B1

MySQL supports thread-specific variables, using @variablename syntax. A variable name can be the alphanumeric character of the current character set and the "_", "$" and "." Composition The default character set is Iso-8859-1 Latin1, which can be changed by recompiling MySQL.
Variables do not have to be initialized. By default, they contain null and can store integers, real numbers, or a string value. When a thread exits, all variables for a thread are automatically freed.

You can set a variable with the SET syntax:

SET @variable = {Integer expression | real expression | string expression}
[, @variable = ...].

You can also use @variable:=expr syntax to set a variable in an expression:

Select @t1: = (@t2: =1) + @t3: =4, @t1, @t2, @t3;
+----------------------+------+------+------+
| @t1: = (@t2: =1) + @t3: =4 | @t1 | @t2 | @t3 |
+----------------------+------+------+------+
|    5 |    5 |    1 | 4 |
+----------------------+------+------+------+

Solution to the problem:
1,
$rs = mysql_query ("Set @t=0");
$rs = mysql_query ("Select Id,name,@t:=@t+1 as P from Tbl_name");
Mysql_result_all ($RS);

2,
$rs = mysql_query ("Set @t= '");
$rs = mysql_query ("Select Name,@t:=concat (@t,", name) as p from Tbl_name);
Mysql_result_all ($RS);



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.