问题
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.
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);
Then like this
if ($STH->rowCount() > 0) {
$result = $STH->fetch(PDO::FETCH_ASSOC);
echo $result['columnfoo'];
echo $result['anothercolumn'];
echo etc.
.
.
.
}
This return errors about sql syntax....
I also tried something like this:
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?
回答1:
You need to use a join
:
SELECT c.*, u.username
FROM client c
JOIN users u ON u.id = c.credid
WHERE credid = :id
来源:https://stackoverflow.com/questions/25721054/mysql-select-all-from-one-table-and-one-column-form-another-where-var-is-foun