[英]Multi valued attributes in a table
我设计了一个发送消息系统,在该系统中,用户可以一次将消息发送给多个人。 因此,邮件的收件人属性是多值的。 所以我设计了另一个表message_recipients。
这是我的桌子:
create table `message`(
`message_id` INT(11) NOT NULL primary key auto_increment,
`sender` VARCHAR(32) NOT NULL,
`topic` VARCHAR(100) NOT NULL,
`content` TEXT NOT NULL,
`message_date` TIMESTAMP NOT NULL ,
`readed` VARCHAR(1) NOT NULL DEFAULT 0,
`deleted_by_sender` VARCHAR(1) NOT NULL DEFAULT 0,
`deleted_by_recipient` VARCHAR(1) NOT NULL DEFAULT 0,
FOREIGN KEY(sender) REFERENCES users(user_name)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
create table `message_recipients`(
`message_id` INT NOT NULL ,
`recipient` VARCHAR(32) NOT NULL ,
PRIMARY KEY(message_id,recipient),
FOREIGN KEY(message_id) REFERENCES message(message_id) on delete cascade,
FOREIGN KEY(recipient) REFERENCES users(user_name)
)ENGINE=InnoDB default charset=utf8;
当我在message
表中插入一条消息时,我需要获取其message_id
并将其与一个或多个收件人一起插入message_recipients
表中。
这是我的脚本:
insert into `message`(`sender`,`topic`,`content`)
values('me','need help','how to get last inserted row');
select message_id from `message` order by `message_id` desc limit 0,1;
当我收到message_id
,现在可以将其插入到message_recipients
,并以某些用户作为收件人,现在的问题是; 有没有更好或更优化的方法?
使用函数mysql_insert_id()代替
select message_id from `message` order by `message_id` limit 0,1;
这是一个内置的MySQL方法,将为您提供刚刚插入的主键。 如果存在大量同时插入,则上面的SELECT语句可能不可靠。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.