这种关系是否可行(phpmyadmin)

时间:2012-12-01 11:15:29

标签: php phpmyadmin

是否可以这样做?

table1的列名为“id” table2也有一个列名'id'。

因为table2接受来自所选复选框的多个值,我想将它与table1相关联。 table1包含firstname lastname等,而table2包含复选框中的选定值(选择1个或多个)。

表1

id  |   firstname   |  lastname

1   |   John        |   Conner

表2

id   |  sports

1    |  basketball

2    |  volleyball

3    |  tennis

john从复选框中选择了3个值...

如何关联或使第一个插入的数据拥有3个值或将显示如下:

id  |  firstname   |   lastname   |   sports

1   |   John       |   Conner     |   basketball

|排球-------->

|网球------------->

提前谢谢...... 对不起插图。

2 个答案:

答案 0 :(得分:0)

为此,您需要Many to Many relationship

你需要一个第三个表来保持其他两个之间的关系。

答案 1 :(得分:0)

您需要第3个表格,将用户与体育相关联。

connections
--------------------------
id | users_id  | sports_id
1  | 1         | 1
2  | 1         | 2
3  | 2         | 1
--------------------------

上表将用户#1连接到体育#1和#2,用户#2连接到体育#1。 (我从你的问题重命名表格,使我的例子更具可读性:table1 - > users和table2 - > sports)

要使用此方法合并记录,您可以调用

SELECT users.firstname, users.lastname, sports.sports
FROM connections
JOIN users ON connections.users_id = users.id
JOIN sports ON connections.sports_id = sports.id

这也可以让您显示从列表中选择特定运动的用户。这样,您也可以编辑一次体育名称,同时影响所有结果。

使用PHP / MySQLi的工作示例

$db = new mysqli('localhost', 'user', 'pass', 'database'); // Database connection
if ($db->connect_errno > 0) { // Do we have a connection?
    die('Unable to connect to database [' . $db->connect_error . ']');
}
// Set the sql query
$sql = "SELECT users.firstname, users.lastname, sports.sports
    FROM connections
    JOIN users ON connections.users_id = users.id
    JOIN sports ON connections.sports_id = sports.id";

if (! ($result = $db->query($sql))) { // Run the query, get results to $result, if errors die
    die('There was an error running the query [' . $db->error . ']');
}
while (($row = $result->fetch_assoc())) { // Loop through the results and echo
    echo $row['firstname'] . ' ' . $row['lastname'] . ' likes ' . $row['sports'] . '<br />';
    // To see all $row variables in nice format we can do: echo '<pre>' . print_r($row, true) . '</pre>';
}

我添加了Kyle Reese作为用户ID#2,因此我的查询结果的输出将是:

John Conner likes basketball
John Conner likes volleyball
Kyle Reese likes basketball