正确的数据库?它需要改变吗?

时间:2012-09-17 10:42:56

标签: mysql database database-design foreign-keys

我正在创建一个页面,我希望用户能够为活动预订座位。


  • 1位用户只能预订1个席位
  • 用户在登录后没有选择座位,首先是购买到现场后
  • 需要能够清理座位表,而不会丢失用户表中的任何内容(当然除了指定的座位。)

我已经创建了两个表,因为我对mySQL很新,我想检查一下这是否正确完成:

  • 部件表:
  • user_id int(8)非null auto_increment
  • user_name varchar(30)非空
  • user_pass varchar(255)不为空
  • seat_ID smallint(6)是NULL

  • 座位表
  • seat_ID smallint(6)没有auto_increment
  • user_id smallint(6)是NULL
  • seat_status tinyint(4)是NULL
  • seat_status tinyint(4)是NULL

我创建了2个FK-refs:

ALTER TABLE seats
ADD CONSTRAINT FK_seats  
FOREIGN KEY (user_id) REFERENCES members(user_id)  
ON UPDATE CASCADE  
ON DELETE CASCADE;

ALTER TABLE seats
ADD CONSTRAINT FK_seats  
FOREIGN KEY (seat_ID) REFERENCES members(seat_ID)  
ON UPDATE CASCADE  
ON DELETE CASCADE;

我是否在正确的轨道上?通过这种设置,我能够获得不错的最终产品吗?建议/改进?我不想在几周内重新开始,因为数据库结构质量很差。

2 个答案:

答案 0 :(得分:2)

首先,如果任何用户在任何给定时间只能容纳一个席位,我不明白为什么要使用第二个表格,其次user_idseats-table的大小应与会员表中的user_idint(8),否则您将无法在一段时间内暂住用户,第三个问题是seat_status的重复,我认为这是一个错误,或者您有另一个名称。 在我看来,更好的想法是使用单个表格,如果它是1> 1映射并将其定义为

CREATE TABLE `members-table` (
   user_id int(8) not null auto_increment,
   user_name varchar(30) not null,
   user_pass varchar(255) not null,
   seat -- your type choice, should be nullable if not seated
);

使用此配置清理座位就像

一样简单
UPDATE `members-table` SET `seat` = NULL;

答案 1 :(得分:0)

CREATE TABLE `seats` (
   id int(4) unsigned not null auto_increment primary key,
   row int(2) unsigned not null,
   col int(2) unsigned not null,
   UNIQUE(row, col)
) ENGINE InnoDB;

CREATE TABLE `members` (
   user_id int(8) not null auto_increment primary key,
   user_name varchar(30) not null,
   user_pass varchar(255) not null,
   seat int(4) unsigned null,
   FOREIGN KEY(seat) references seats(id) on delete set null on update restrict,
   UNIQUE(seat)
) ENGINE InnoDB;

您必须使用所有可用的行和列填充席位数据库,在插入时使用null来使用auto_increment功能!

检查是否有座位

SELECT COUNT(*) AS occupied FROM members WHERE seat = (SELECT id FROM seats WHERE row = :ROW AND col = :COL);

或者在上面的查询中使用SELECT (1 - COUNT(*)) AS vacant,如果它更适合您。

找到第一个免费席位

SELECT MIN(id) FROM seats WHERE NOT EXISTS( SELECT seat FROM members WHERE seat = seats.id);

取消所有席位

UPDATE members SET seat = NULL;