$sql = "select body, stamp from posts where user_id = '$userid' order by stamp desc";
注意:上面的查询工作正常。我想要做的还是从我的用户表中选择用户名,并显示与user_id匹配的用户名。
我已经编辑了上述声明,但它不起作用。有人可以提出正确的查询吗?我的目标是也能够显示用户名。除了简单地显示user_id。
$sql = "select body, stamp from posts AND username from users where user_id = '$userid' order by stamp desc";
我的目标是也能够显示用户名。而不仅仅是user_id。
答案 0 :(得分:4)
您需要使用JOIN将两个表放在匹配字段上,如下所示:
$sql = "SELECT p.body, p.stamp, u.username FROM posts p INNER JOIN users u ON p.user_id=u.user_id WHERE p.user_id='$userid' ORDER BY p.stamp DESC";
答案 1 :(得分:1)
您可以使用表名来选择列。例如:
$Query = "select table1.body, table1.stamp, users.username from posts, users where user_id = '$userid' order by stamp desc";
但是,这种方法的表现并不好。
最好的方法是:
$Query = "SELECT table1.body, table1.stamp, users.username
FROM posts
INNER/LEFT/RIGHT JOIN users
ON users.user_id = '$userid' AND users.user_stamp = stamp.stamp_id
所有表格必须相关。
问候,
答案 2 :(得分:0)
$sql = "select body, stamp from posts , username from users where user_id = '$userid' order by stamp desc";
我刚刚更正了您的查询中的语法错误...即AND关键字应替换为,
。
答案 3 :(得分:0)
$sql = "
select body, stamp from posts where user_id = '$userid' order by stamp desc
UNION ALL
select body, stamp from username where user_id = '$userid' order by stamp desc
";
答案 4 :(得分:0)
select body, stamp, username
from posts,users
where users.user_id = post.user_id
and users.user_id = '$userid'
order by stamp desc;
答案 5 :(得分:0)
您应该使用别名或表名来避免像这样的重复问题
tablename.column
或
alias.column
您可以在where子句中设置别名:
FROM table as alias_name
答案 6 :(得分:0)
$sql = "SELECT p.body,p.stamp,u.username from posts p LEFT JOIN users as u ON (p.user_id = u.user_id) WHERE user_id = '$user_id' ORDER BY p.stamp DESC";
应该这样做
答案 7 :(得分:0)
试试这个:
select body, stamp, username
from posts p JOIN users a ON p.user_id = a.user_id
WHERE p.user_id = '$userid' order by stamp desc
答案 8 :(得分:0)
这应该可以正常工作:
SELECT posts.body, posts.stamp, users.username
FROM posts, users
WHERE posts.user_id = '$userid' AND posts.user_id = users.user_id
ORDER BY posts.stamp DESC