[英]Multi valued attributes in a table
I have designed a send message system in which users can send a message to more than one person at a time. 我设计了一个发送消息系统,在该系统中,用户可以一次将消息发送给多个人。 so the recipient attribute of a message is multi valued.
因此,邮件的收件人属性是多值的。 so i designed an other table called message_recipients.
所以我设计了另一个表message_recipients。
Here are my tables: 这是我的桌子:
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;
When i insert a message in message
table i need to get its message_id
and insert it with recipient or recipients into message_recipients
table. 当我在
message
表中插入一条消息时,我需要获取其message_id
并将其与一个或多个收件人一起插入message_recipients
表中。
Here is my script: 这是我的脚本:
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;
When i got the message_id
, i can now insert it into message_recipients
with some users as recipient, and now question is that; 当我收到
message_id
,现在可以将其插入到message_recipients
,并以某些用户作为收件人,现在的问题是; is there any better or more optimized way? 有没有更好或更优化的方法?
Use the function mysql_insert_id() instead of 使用函数mysql_insert_id()代替
select message_id from `message` order by `message_id` limit 0,1;
This is a built-in MySQL method that will get you the just inserted primary key. 这是一个内置的MySQL方法,将为您提供刚刚插入的主键。 The SELECT statement above might not be reliable if there are a large number of simultaneous inserts.
如果存在大量同时插入,则上面的SELECT语句可能不可靠。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.