dongquanjie9328 2010-11-09 14:09
浏览 52
已采纳

将一个表连接到许多表

I am building a commenting system where people can comment on uploaded files, messages and to-do items. What is the best way to connect the comment table table to the other various tables?
Possible Solutions
Solution one - use a two field foreign key.

CREATE TABLE `comments`(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
foreign_key INT NOT NULL,
table_name enum('files','messages','to-do'),
user_id INT NOT NULL,
comment TEXT NOT NULL);

Solution two - Each table would have a primary key unique to the database. So I would use php's uniqid($prefix) as the primary keys for each table.

CREATE TABLE `comments`(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
foreign_key char(23) NOT NULL,
table_name enum('files','messages','to-do'),
user_id INT NOT NULL,
comment TEXT NOT NULL);

Solution Three - Have multiple foreign keys in the comment table

CREATE TABLE `comments`(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
files_id INT NOT NULL,
messages_id INT NOT NULL,
to_do_id INT NOT NULL,
user_id INT NOT NULL,
comment TEXT NOT NULL);

What is the best solution? I appreciate your input and please let me know if I can clarify anything

EDIT removed table_name from solution three as it was a copy_paste error As to Joe's Response

Assume: 1) all data is already escaped. Do we really need to see that?
2) $fileId = "146".
3) $userId = "432".
4) $comment = "Stackoverflow is so awesome!"

INSERT

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
 mysql_select_db('mydb');
 mysql_query("INSERT INTO `comments` (user_id,comment) VALUES($userId,$comment)");
 $commentId = mysql_insert_id();
 mysql_query("INSERT INTO `comments_files_xref` (file_id,comment_id)         VALUES($fileId,$commentId)");
  • 写回答

4条回答 默认 最新

  • dongshiliao7990 2010-11-09 14:30
    关注

    Personally, I would normalize the design a bit more. Perhaps something like:

    alt text

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分