2015-12-11 26 views
0

有沒有什麼辦法可以完成下面的sql結果作爲一個班輪。設置這個/下一個auto_increment值的列值

create table test(id int not null primary key auto_increment, name char(10)); 

insert into test (name) values ('voda'+ this_value_of_id); 

// so select would return 
MariaDB [testdb]> select * from test; 
+----+------+ 
| id | name | 
+----+------+ 
| 1 | foo1 | 
+----+------+ 

是的,我知道的另一種方式是

begin transaction; 
insert into test (name) values ('voda'); 
update test set name = concat('voda', id) where id = 1; 
commit; 
+0

我建議你不要做它。真正以數字結尾的名稱會引起混淆。你可以隨時選擇連接結果。如果你想經常做,創建一個函數。 –

+0

那麼有一種方法,但我也認爲@DanBracuk是對的,你不應該這樣做。方法是從schema_information中選擇auto_increment值並連接。在這裏看到:http://stackoverflow.com/questions/15821532/get-current-auto-increment-value-for-any-table –

+0

@DanBracuk擴大的情況。我的情況來自需要在(http)請求發出時創建臨時用戶。然後我們有每小時運行一次的cron作業並刪除臨時用戶。我解決了這個問題:'begin transaction; (替換(concat(sysdate(6),rand(7)),'',' - '),':',' - '),'。',' - '))更新用戶集username = concat(usertemp,id)其中id = user_id_of_upper_query;提交;'用戶名顯然是唯一的(唯一索引列)。剛剛第一次查詢後的數據,只有用戶名:'2015-12-11-19-52-15-3540820-9065021936842261' – broadband

回答

2

選項或方法可以通過Virtual (Computed) Columns

例子:

MariaDB [testdb]> DROP TABLE IF EXISTS `test`; 
Query OK, 0 rows affected (0.00 sec) 

MariaDB [testdb]> CREATE TABLE `test` (
    -> `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, 
    -> `name` CHAR(10), 
    -> `nameid` VARCHAR(20) AS (CONCAT(`name`, `id`)) VIRTUAL 
    ->); 
Query OK, 0 rows affected (0.00 sec) 

MariaDB [testdb]> INSERT INTO `test` 
    -> (`name`) 
    -> VALUES 
    -> ('foo'), ('voda'); 
Query OK, 2 rows affected (0.00 sec) 
Records: 2 Duplicates: 0 Warnings: 0 

MariaDB [testdb]> SELECT 
    -> `id`, 
    -> `nameid` `name` 
    -> FROM 
    -> `test`; 
+----+-------+ 
| id | name | 
+----+-------+ 
| 1 | foo1 | 
| 2 | voda2 | 
+----+-------+ 
2 rows in set (0.00 sec)