与用户 table 相关的外键 SQL
Foreign Keys SQL relational to user table
我正在尝试了解外键并能够将数据从一个 table 关联到另一个。所以我有一个用户 table 和一个卡片 table.
用户 table 有 'user_id'、'username' 和 'email'。
卡片 table 有 'card_id' & 'name'.
我要做的是将卡片 table 中的卡片关联到用户。因此,例如,如果卡 table 内有 Card1 并且 user1 想要该卡(或更多)与他们相关联,我将如何使用外键来执行此操作。
这是我目前选择和展示我的用户的方式:
<?php
$sql = "SELECT user_id, username, email_address FROM user";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
$row["username"] . "<br>",
$row["email_address"] . "<br><br>";
}
} else {
echo "0 Members";
}
$conn->close();
?>
我理解用户的内心 table 我需要另一个单元格 'card_id' 但不确定这应该是哪种数据类型?
根据您的问题和您的以下评论:
so the cards table is reffering to playing cards. A user can collect
the cards so they become a part of the users deck essentially. I want
a way for the card to be associated to the user.
我相信您可以通过两种方式实现这一目标,具体取决于您 game/script 中的进一步场景。
场景 1:
如果一张卡只能属于一个用户。
将新字段添加到 cards table
.
`user_id` INT(11)
当用户收集卡片时,只需更新该字段即可存储用户的 ID。
场景二:
如果一张卡可以属于多个用户。
创建一个名为 users_cards
的新 table:
users_card
- id (INT)
- user_id (INT)
- cart_id (INT)
当用户收集卡片时,向卡片插入一条新记录table,同时包含卡片 ID 和用户 ID。
我正在尝试了解外键并能够将数据从一个 table 关联到另一个。所以我有一个用户 table 和一个卡片 table.
用户 table 有 'user_id'、'username' 和 'email'。 卡片 table 有 'card_id' & 'name'.
我要做的是将卡片 table 中的卡片关联到用户。因此,例如,如果卡 table 内有 Card1 并且 user1 想要该卡(或更多)与他们相关联,我将如何使用外键来执行此操作。
这是我目前选择和展示我的用户的方式:
<?php
$sql = "SELECT user_id, username, email_address FROM user";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
$row["username"] . "<br>",
$row["email_address"] . "<br><br>";
}
} else {
echo "0 Members";
}
$conn->close();
?>
我理解用户的内心 table 我需要另一个单元格 'card_id' 但不确定这应该是哪种数据类型?
根据您的问题和您的以下评论:
so the cards table is reffering to playing cards. A user can collect the cards so they become a part of the users deck essentially. I want a way for the card to be associated to the user.
我相信您可以通过两种方式实现这一目标,具体取决于您 game/script 中的进一步场景。
场景 1:
如果一张卡只能属于一个用户。
将新字段添加到 cards table
.
`user_id` INT(11)
当用户收集卡片时,只需更新该字段即可存储用户的 ID。
场景二:
如果一张卡可以属于多个用户。
创建一个名为 users_cards
的新 table:
users_card
- id (INT)
- user_id (INT)
- cart_id (INT)
当用户收集卡片时,向卡片插入一条新记录table,同时包含卡片 ID 和用户 ID。