mysql - 从一个表中选择所有,从另一个表中选择一个列,其中找到 $var [英] mysql - Select all from one table and one column form another where $var is found

查看:33
本文介绍了mysql - 从一个表中选择所有,从另一个表中选择一个列,其中找到 $var的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哦哦哦哦.我有两个表客户端和用户.两者都有 AUTO_INCREMENT id,但客户端表有 credid-column ,它是外键和对用户表 id 的引用.

Ooooookay. I have two tables client and users. Both have AUTO_INCREMENT id but client table has credid-column whis is foreign key and references to users table's id.

我想准备一个 PHP PDO 语句,它从客户端表中获取所有列,并且只从用户表中获取用户名列,其中客户端表的列 credid = :var 和用户表的列 id = :var

I want to prepare a PHP PDO statement that fetches all columns from client-table and only username-column from users-table where client table's column credid = :var and user table's column id = :var

到目前为止,我有这样的东西,但它不工作

So far I have something like this and it is not working

$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 语法的错误......

This return errors about sql syntax....

我也试过这样的:

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

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

Returns no errors but not any data either... How should I construct my prepared query?

推荐答案

你需要使用一个join:

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

这篇关于mysql - 从一个表中选择所有,从另一个表中选择一个列,其中找到 $var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆