使用条件组ID生成前缀编号ID

时间:2015-04-08 16:45:03

标签: mysql concat zerofill

首先这是我的表

CREATE TABLE IF NOT EXISTS `group` (
    `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
    `name` varchar(255) NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `member` (
    `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
    `group_id` int(11) unsigned NOT NULL,
    `code` int(11) NOT NULL,
    `name` varchar(255) NOT NULL,
    PRIMARY KEY (`id`),
    KEY `group_id` (`group_id`),
    FOREIGN KEY (`group_id`) REFERENCES `group` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

我需要member.id看起来像001,002,003。我关注lpad(id, 3, 0)和案件结束

但是如何将001,002,003再次重置为001,其中有group_id

此查询的结果为01-001,01-002,02-003,03-004(group.id - member.id

SELECT CONCAT(lpad(g.id, 2, 0),'-',lpad(m.id, 3, 0)) AS id, m.name
FROM member m
LEFT JOIN group g ON g.id = m.group_id
ORDER BY m.id ASC

请帮忙,我需要01-001,01-002,02-001,03-001(group.id - member.id

或者我可以使用触发器在member.code - group.id <基础上插入01-001,01-002,02-003,03-004时自动生成member.id / p>

0 个答案:

没有答案