您需要将用户与运动联系起来的第三张桌子。
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