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.
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.
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; is there any better or more optimized way?
Use the function mysql_insert_id() instead of
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. The SELECT statement above might not be reliable if there are a large number of simultaneous inserts.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.