Well, I have a situation that I need to SELECT
data from two tables at once. But my main problem is how can I SELECT .. WHERE
in my table2 when the value that I needed in WHERE clause
is in the return value of SELECT
statement in table1.
好吧,我有一种情况需要一次从两个表中选择数据。但我的主要问题是当我在WHERE子句中需要的值在table1中的SELECT语句的返回值时,我如何在table2中SELECT .. WHERE。
test.php
test.php的
<?php
include("../../connection.php");
$data = json_decode(file_get_contents("php://input"));
$id= $data->id;
try{
$db->exec("SET CHARACTER SET utf8");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "
SELECT * FROM tblstudents WHERE studID=':id';
SELECT * FROM tblparents WHERE studNumber=':studNumber';
";
$statement = $db->prepare($sql);
$statement->bindValue(":id", $id);
$statement->bindValue(":studNumber", $studNumber);
$result = $statement->execute();
echo json_encode($result);
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
The studNumber
value is in the tblstudents
which will have a return value from SELECT
statement.
studNumber值位于tblstudents中,它将具有SELECT语句的返回值。
Is it possible that I can get the studNumber
value in the return value of SELECT
statement when the SELECT
statement of the tblparents
is in the same sql query
? Or is there another way around?
当tblparents的SELECT语句在同一个sql查询中时,我是否可以在SELECT语句的返回值中获取studNumber值?或者还有另一种方法吗?
Hope I clearly explained my situation.
希望我清楚地解释了我的情况。
1 个解决方案
#1
1
You need to use JOIN
for get data from multiple tables. Try this query:
您需要使用JOIN从多个表中获取数据。试试这个查询:
$sql = "SELECT * FROM tblstudents JOIN tblparents on
tblstudents.studNumber = tblparents.studNumber WHERE tblstudents.studID=:id;"
$statement = $db->prepare($sql);
$statement->bindValue(":id", $id);
$result = $statement->execute();
#1
1
You need to use JOIN
for get data from multiple tables. Try this query:
您需要使用JOIN从多个表中获取数据。试试这个查询:
$sql = "SELECT * FROM tblstudents JOIN tblparents on
tblstudents.studNumber = tblparents.studNumber WHERE tblstudents.studID=:id;"
$statement = $db->prepare($sql);
$statement->bindValue(":id", $id);
$result = $statement->execute();