php - 如何将这些多个 mysql_querys 转换为 1 个查询?

标签 php mysql sql join

我有两个表:用户和线程。创建线程时,它会将 user_id 作为 author_id 存储在表中。我想用相同的查询显示线程名称和作者的用户名。我目前正在使用两个查询,如下所示:

$query2 = mysql_query("SELECT author_id FROM threads WHERE id = $threadId") or die(mysql_error());
$result2 = mysql_fetch_array($query2);
$author_id = $result2['author_id'];
$query3 = mysql_query("SELECT username FROM users WHERE id = $author_id") or die(mysql_error());
$result3 = mysql_fetch_array($query3);
$author_name = $result3['username'];

最佳答案

<?php
$sql = '
    SELECT t.name, u.username
    FROM threads t
    JOIN users u ON t.author_id = u.id
    WHERE t.id = ' . (int)$threadId . '
';
list($thread_name, $author_name) = mysql_fetch_row(mysql_query($sql));

附言Mysql php extension已弃用。

关于php - 如何将这些多个 mysql_querys 转换为 1 个查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34303352/

相关文章:

mysql - 只允许一个唯一的外键作为主键

php - 有哪些更有效的方法来处理查询?

javascript - Angular 请求 api 以及 token

php - 从多个表中选择行的最佳方法?

mysql - 如果多个表满足条件,如何获取ID

mysql - MySQL 5.5 中的语法错误

sql - 将具有相同 ID 的多行合并为一行

php - Laravel 5.1 将关系数据加载到选定行

php - 如何检查数组是否有 [0] 索引但没有值?

sql - T-SQL 中数字类型的优先级