我有两张桌子:
任务:
id title description client_id
客户:
id name phone email url
当我点击我的PHP应用程序中的任务时,我打开一个新页面,我也发送所点击任务的ID。
要从我的表格中获取信息,请执行以下操作:
$task_id = null;
if (! empty ( $_GET ['task_id'] )) {
$task_id = $_GET ['task_id'];
}
if ($task_id == null) {
die("This page can only be accessed by selecting a task");
}
$sql = "SELECT * FROM task WHERE id=:id";
$query = $db->prepare ( $sql );
$query->bindParam ( ":id", $task_id );
$query->execute ();
$task = $query->fetch ();
$client_id = $task ["client_id"];
$sql = "SELECT * FROM clients WHERE id=:client_id";
$query = $db->prepare ( $sql );
$query->bindParam ( ":client_id", $client_id );
$query->execute ();
$client = $query->fetch ();
所以,我的问题是,我可以使用一个SELECT代替当前的两个吗?
答案 0 :(得分:1)
当然,您可以加入这两张桌子。查询将如下所示:
SELECT *
FROM task
LEFT JOIN clients
ON task.client_id=clients.id
WHERE task.id=:id
或者在你的PHP中:
$sql = "SELECT * FROM task LEFT JOIN clients ON task.client_id=clients.id WHERE task.id=:id";
$query = $db->prepare ( $sql );
$query->bindParam ( ":id", $task_id );
$query->execute ();
$task = $query->fetch ();
答案 1 :(得分:1)
是的,您可以使用子查询或Robby建议使用连接。 子查询示例:
$sql = "SELECT * FROM clients WHERE id = (SELECT client_id FROM task WHERE :task_id LIMIT 1)";
$query = $db->prepare ( $sql );
$query->bindParam ( ":task_id", $task_id );
$query->execute ();
$client = $query->fetch ();
哪一项更合适可能取决于您的使用案例。如上所述,要么应该解决你的问题。