如何在mysql中为identity列添加前缀。

时间:2014-03-11 17:42:10

标签: mysql sql phpmyadmin

在这里,我试图在mysql数据库中自动增加我的标识列,如下所示,在数字前添加前缀。

标识------------------类别

Cat10001 ---------男性
Cat10002 --------女性
Cat10003 ---------儿童

这里是我提到的link这样做但是我挂了一个错误

错误: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS 'ABCD-' + CAST(Id as varchar(16)) )' at line 4

MySql查询:

CREATE TABLE MyTable
(
    Id int NOT NULL PRIMARY KEY,
    categoryid AS 'cat' + CAST(Id as varchar(16)) 
)

注意:我使用的是PhpMyadmin mysql。

3 个答案:

答案 0 :(得分:2)

您可以使用BEFORE INSERT触发器。你可以做这样的事情。请检查下方是否符合您的要求。

CREATE TABLE MyTable
(
    Id int NOT NULL PRIMARY KEY AUTO_INCREMENT,
    categoryid varchar(16),
    categoryname varchar(16)
);

CREATE TRIGGER mytrigger
  BEFORE INSERT
  ON MyTable
  FOR EACH ROW
  SET NEW.categoryid = 
  CONCAT("CAT",COALESCE((SELECT MAX(Id)+1 from MyTable),1));

insert into MyTable(categoryid,categoryname) Values(1,"test");
insert into MyTable(categoryid,categoryname) Values(2,"test1");

答案 1 :(得分:0)

创建视图或单独的表以获得此类数据。像

create view calculateddata
as
select Id,
concat('cat',CAST(Id as varchar(16))) AS categoryid
from MyTable

答案 2 :(得分:0)

MySQL不支持计算列,因此需要使用视图。

你应该在这里阅读答案:Create a computed column based on another column in MySQL

CREATE VIEW your_view
  AS
SELECT Concat('CAT', Cast(Id As varchar(11))) As Id
     , categoryid
FROM   MyTable