我有两个表:用户和线程。创建线程时,它会将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'];
答案 0 :(得分:4)
<?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));
P.S。 {/ 3}}已被弃用。
答案 1 :(得分:1)
尝试此查询:
SELECT username
FROM users
WHERE id = (SELECT author_id
FROM threads
WHERE id = $threadId
LIMIT 1)
注意:Limit 1
不是必需的,因为ID是唯一的。