将查询组合到现有JOIN查询中

时间:2015-09-02 13:13:07

标签: php mysql sql join

我在组合两个SELECT查询时遇到了一些困难。一个是基本查询,另一个是JOIN。我希望使用JOIN查询$stmt_id我的JOIN查询。

$stmt_id查询...

$stmt_id = $con->prepare("SELECT id FROM users WHERE `group` IN (3,4,5)");
if ( !$stmt_id || $con->error ) {
     // Check Errors for prepare
        die('Userid SELECT prepare() failed: ' . htmlspecialchars($con->error));
    }
//if(!$stmt_id->bind_param('i', $userid)) {
    // Check errors for binding parameters
    //    die('Userid SELECT bind_param() failed: ' . htmlspecialchars($stmt_id->error));
    //}
if(!$stmt_id->execute()) {
        die('Userid SELECT execute() failed: ' . htmlspecialchars($stmt_id->error));

    $stmt_id->store_result();
}
$stmt_id->bind_result($userid);

while ($stmt_id->fetch()) {
    echo $userid;
}

这是我的JOIN查询,我想在其中添加$stmt_id查询:

$stmt = $con->prepare("SELECT up.ordering, u.username, up.playername 
FROM users AS u  
INNER JOIN playersByUser AS up ON u.id = up.userid 
WHERE u.id = ?
ORDER BY up.ordering");
if ( !$stmt || $con->error ) {
     // Check Errors for prepare
        die('User/Player SELECT prepare() failed: ' . htmlspecialchars($con->error));
    }
if(!$stmt->bind_param('i', $userid)) {
    // Check errors for binding parameters
        die('User/Player SELECT bind_param() failed: ' . htmlspecialchars($stmt->error));
    }
if(!$stmt->execute()) {
        die('User/Player SELECT execute() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->bind_result($ordering, $username, $playername);

我知道uquery必须在查询的SELECT部分中包含id,但我不确定如何修改此行..

  WHERE u.id = ?

要在$stmt_id查询...

中加入此内容
SELECT id FROM users WHERE `group` IN (3,4,5)")

这是我尝试过的,而且我坚持......

$stmt = $con->prepare("SELECT up.ordering, u.id, u.username, up.playername 
FROM users AS u  
INNER JOIN playersByUser AS up ON u.id = up.userid 
WHERE u.id = ?
ORDER BY up.ordering");
if ( !$stmt || $con->error ) {
     // Check Errors for prepare
        die('User/Player SELECT prepare() failed: ' . htmlspecialchars($con->error));
    }
if(!$stmt->bind_param('i', $userid)) {
    // Check errors for binding parameters
        die('User/Player SELECT bind_param() failed: ' . htmlspecialchars($stmt->error));
    }
if(!$stmt->execute()) {
        die('User/Player SELECT execute() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->bind_result($ordering, $username, $playername);

0 个答案:

没有答案