mysql - 从一个表中选择所有表,从另一个表中选择一列,其中找到$ var

时间:2014-09-08 09:27:15

标签: sql prepared-statement fetch multi-table

Ooooookay。我有两个表客户端和用户。两者都有AUTO_INCREMENT id但客户端表有credid-column whis是外键并且引用了users表的id。

我想准备一个PHP PDO语句,它从client-table中获取所有列,而只从users-table中获取username-column,其中client table的列credid =:var和user table的列id =:var

到目前为止,我有类似的东西并且无法正常工作

$userid = $_SESSION['id']; //echoes a number
    $STH = $DBH->prepare("SELECT * FROM client WHERE credid = :id AND username FROM users
    WHERE id = :id");
    $credentials = array(
        ':id' => $userid
    );
    $STH->execute($credentials);

然后像这样

    if ($STH->rowCount() > 0) {
        $result = $STH->fetch(PDO::FETCH_ASSOC);
        echo $result['columnfoo'];
        echo $result['anothercolumn'];
        echo etc.
        .
        .
        .

    }

这返回有关sql语法的错误....

我也试过这样的事情:

    SELECT client.*,users.username FROM client,users WHERE client.credid =users.id = :id

返回没有错误但不返回任何数据...... 我该如何构建我准备好的查询?

1 个答案:

答案 0 :(得分:5)

您需要使用join

SELECT c.*, u.username
FROM   client c
JOIN   users u ON u.id = c.credid
WHERE  credid = :id