ユーザーをスポーツにつなげる第 3 のテーブルが必要です。
connections
--------------------------
id | users_id | sports_id
1 | 1 | 1
2 | 1 | 2
3 | 2 | 1
--------------------------
上記のテーブルは、ユーザー #1 をスポーツ #1 および #2 に接続し、ユーザー #2 をスポーツ #1 に接続します。(私の例を読みやすくするために、あなたの質問からテーブルの名前を変更しました: table1 -> users and 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