php - 我可以将我的 2 个选择查询合并为一个吗?

标签 php mysql sql pdo mysqli

我有 2 个表:

任务:

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 而不是我目前的两个吗?

最佳答案

当然可以,通过连接两个表。查询看起来像这样:

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 ();

关于php - 我可以将我的 2 个选择查询合并为一个吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27221207/

相关文章:

php - 如果字符串包含任何字符,则从数组中删除元素

php - CodeIgniter 中的博客 : Where Does the Model start, 和 Controller 端?

php如何比较一天与近结束时间的比

php - 一般错误 : could not call class constructor'

php - 随机组合 MySQL 数据库中的两个单词

php - 尝试获取项目 id 以与 ajax 一起使用

sql - Apache Spark 中的授权

php - Wordpress - 将联系表单 7 字段作为单独的列保存到数据库中

mysql - 从连接表中按年份查询数据

mysql - AWS Cognito Identity ID 对 SQL 主键的适用性