[英]Facing issues while fetching data from two different mysql tables using a single query..!
I have two tables, one for the posts and another for the users. 我有两个表,一个用于发布,另一个用于用户。 I am fetching all posts from the 'posts' table and user data (who posted that post) from the tbl_users. 我正在从“帖子”表中获取所有帖子,并从tbl_users中获取用户数据(谁发布了该帖子)。
currently, I am using this query : 目前,我正在使用此查询:
$query = $pdo->prepare("SELECT * FROM `posts`,`tbl_users` WHERE id = user_id_p ORDER BY `post_id` DESC");
$query->execute();
return $query->fetchAll();
it is working fine, it is fetching all the posts from the posts table and user data from tbl_users. 它工作正常,正在从posts表中获取所有帖子,并从tbl_users中获取用户数据。 However, my issue is this that I don't want to fetch all posts, but I want to fetch only those posts which are posted by the specific user(for example by John only) and the user data for John only from the tbl_user. 但是,我的问题是我不想提取所有帖子,但是我只想提取特定用户(例如仅John)发布的那些帖子以及仅从tbl_user获取John的用户数据。
(field Id from tbl_users and field user_id_p from the table posts are same in both the tables.) (来自tbl_users的字段ID和来自表帖子的user_id_p字段在两个表中都是相同的。)
Any suggestions or help? 有什么建议或帮助吗?
Although your query is working , it is not at all efficient because it uses an implicit cross join which results in a very large resultset. 尽管您的查询有效 ,但由于使用隐式交叉联接会导致非常大的结果集,因此它根本没有效率。
Use a proper INNER JOIN with a condition applied with WHERE
: 使用适当的INNER JOIN并在WHERE
施加条件:
SELECT u.*, p.*
FROM tbl_users u INNER JOIN posts p
ON u.id = p.user_id_p
WHERE u.id = ?
ORDER BY p.post_id DESC
Replace ?
更换?
with the id of the user. 与用户的ID。
You can use JOIN
for this. 您可以为此使用JOIN
。 Example 例
select P.name, U.name from post P NATURAL JOIN user U;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.