我有以下代码(你不需要知道很多查询来得到我的问题):
if ($stmt = $cxn->prepare('SELECT p.post_id, p.reply_to, p.parent_id, p.post_path, p.user_id, p.content, p.datetime, p.total_likes, p.total_replies, p.total_reposts, l.like_id, l.user_id, u.username, u.display_name
FROM posts p
LEFT JOIN users u ON p.user_id = u.user_id
LEFT JOIN likes l ON l.post_id = p.post_id
WHERE l.user_id IN
(SELECT user_id FROM likes WHERE user_id IN
(SELECT following_id FROM follows WHERE user_id = ? AND following_id != ?))
AND l.user_id != p.user_id AND p.removed != 1
ORDER BY p.datetime DESC LIMIT 26')) {
$stmt->bind_param('ii', $id, $id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($post_id, $reply_to, $parent_id, $post_path, $user_id, $content, $datetime, $total_likes, $total_replies, $total_reposts, $like_id, $like_user_id, $username, $display_name);
}
现在,我有l.user_id
值,即用户的整数值。
如果我已经l.user_id
查询了users
,我将如何添加到此查询以便从u.username
表中获取p.user_id
的用户名?< / p>
谢谢!
答案 0 :(得分:1)
您可以使用别名来实现此目的,它们可以在您的情况下使用,例如
SELECT l.user_name as user, u.username as uname, ....
来自文档
SQL别名
SQL别名用于为数据库表或表中的列提供临时名称。
基本上创建了别名以使列名更具可读性。
了解详情here
答案 1 :(得分:0)
试试这个
if ($stmt = $cxn->prepare('SELECT p.post_id, p.reply_to, p.parent_id, p.post_path, p.user_id, p.content, p.datetime, p.total_likes, p.total_replies, p.total_reposts, l.like_id, l.user_id, l.username as lusername , u.username, u.display_name
FROM posts p
....
编辑:
更改此
LEFT JOIN likes l ON l.post_id = p.post_id
到
LEFT JOIN likes l ON l.post_id = p.post_id AND l.user_id= u.user_id