具有赋值和自动增量的MySQL语句如何工作?

时间:2015-08-10 04:17:42

标签: mysql auto-increment

我使用此代码从1(序列号)开始分配和自动增量。但实际上不知道它是如何工作的,它有什么好处。

    select cast((@cnt := @cnt + 1) as char(10)) as sno, temp1.*
    from
    (
        ..............
    )temp1, (SELECT @cnt := 0) AS dummy

1 个答案:

答案 0 :(得分:0)

select cast((@cnt := @cnt + 1) as char(10)) as sno, temp1.*
from
(
    ..............
)temp1, (SELECT @cnt := 0) AS dummy

与:

相同
select cast((@cnt := @cnt + 1) as char(10)) as sno, temp1.*
    from
    (
        ..............
    )temp1
    CROSS JOIN (SELECT @cnt := 0) AS dummy

&安培;请注意,FROM CLAUSE是在SELECT

之前执行的

所以会发生的是,作为@cnt占位符的虚拟列被添加到其他表的每一行。然后在select子句中,@ cnt对结果集中的每一行加1。

SQL Fiddle

MySQL 5.6架构设置

CREATE TABLE Temp1
    (`id` int, `productName` varchar(7), `description` varchar(55))
;

INSERT INTO Temp1
    (`id`, `productName`, `description`)
VALUES
    (11, 'OpenIDM', 'Platform for building enterprise provisioning solutions'),
    (322, 'OpenAM', 'Full-featured access management'),
    (4763, 'OpenDJ', 'Robust LDAP server for Java')
;

查询1

select *
from temp1
CROSS JOIN (SELECT @cnt := 0) AS dummy

<强> Results

|   id | productName |                                             description | @cnt := 0 |
|------|-------------|---------------------------------------------------------|-----------|
|   11 |     OpenIDM | Platform for building enterprise provisioning solutions |         0 |
|  322 |      OpenAM |                         Full-featured access management |         0 |
| 4763 |      OpenDJ |                             Robust LDAP server for Java |         0 |

查询2

select cast((@cnt := @cnt + 1) as char(10)) as sno, temp1.*
from temp1
CROSS JOIN (SELECT @cnt := 0) AS dummy

<强> Results

| sno |   id | productName |                                             description |
|-----|------|-------------|---------------------------------------------------------|
|   1 |   11 |     OpenIDM | Platform for building enterprise provisioning solutions |
|   2 |  322 |      OpenAM |                         Full-featured access management |
|   3 | 4763 |      OpenDJ |                             Robust LDAP server for Java |