mysql从两个不同的表中选择. [英] mysql Selecting from two different tables.

查看:65
本文介绍了mysql从两个不同的表中选择.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$sql = "select body, stamp from posts where user_id = '$userid' order by stamp desc";

注意:上面的查询工作正常.我还想从用户表中选择用户名,并显示与user_id匹配的用户名.

NOTE: the above query works fine. What I want to do is also select username from my users table, and display the username that matches the user_id.

我已经像上面那样编辑了上面的语句,但它不起作用.有人可以提出正确的查询吗?我的目标是也能够显示用户名.除了简单地显示user_id.

I have edited the above statement like so, and it doesnt work. Can someone suggest the correct query? My goal is to also be able to display usernames. in addition to simply displaying user_id.

$sql = "select body, stamp from posts AND username from users where user_id = '$userid' order by stamp desc";

我的目标是也能够显示用户名.而不是简单的user_id.

My goal is to also be able to display usernames. instead of simply user_id.

推荐答案

您需要使用JOIN将两个表放在匹配字段上,例如:

You'll need to use a JOIN to bring the two tables together on the matching field, so something like:

$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";

这篇关于mysql从两个不同的表中选择.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆