[英]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.