从MySQL 2个不同的表中查询时如何做多个?

时间:2019-07-08 22:36:57

标签: php mysql

如何从2个不同的表中查询多个内容?

我的代码现在看起来像这样:

$query = "SELECT * FROM user_group WHERE email = '$email'";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
$group = $row['group'];

$sql = "SELECT * FROM matches WHERE group_name1 = '$group' OR group_name2 = '$group'";
$result = $connection->query($sql);

if ($result->num_rows > 0) {

    while($row = $result->fetch_assoc()) {
//some HTML code
}
  }
?>

这是可行的,但由于第一个查询(?),在匹配表中仅显示一行,我在其中获得了'$ row ['group'];'

1 个答案:

答案 0 :(得分:0)

您需要遍历第一个查询的所有结果,然后在循环中执行第二个查询。

但是最好将两个查询合并为一个。

$query = "
    SELECT m.col1, m.col2, m.col3, ...
    FROM matches AS m
    JOIN user_group AS g ON g.group IN (m.group_name1, m.group_name2)
    WHERE g.email = ?";
$stmt = $connection->prepare($query);
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($col1, $col2, $col3, ...);
while ($stmt->fetch()) {
    // some code that uses the variables $col1, $col2, $col3, ...
}

用表中的实际列名替换col1col2col3等。