简体   繁体   English

如何用mysql查询连接两个表?

[英]How to join two tables together with mysql query?

This is a pretty individual question. 这是一个非常个人化的问题。 So I had a hard time finding a good answer on Stack. 所以我很难在Stack上找到一个好的答案。 I'm looking to run a query that combines the information on two tables together. 我希望运行一个将两个表的信息组合在一起的查询。

So far this is what I got 到目前为止,这就是我所得到的

$query = "SELECT blog_post.*, user.name, user.last_name, user.picture 
          FROM blog_post, user 
          INNER JOIN user ON blog_post.author_id = user.id 
          WHERE blog_post.author_id = ? 
          ORDER BY timestamp DESC LIMIT 10";

$Statement = $this->Database->prepare($query);
$Statement->execute(array($id));
$row = $Statement->fetchAll();

print_r($row); //Returns: Array( )

I need to display the user information along with the blog post. 我需要显示用户信息以及博客文章。 I could store the information when I save the post in the database but then it wouldn't update if the user updated their information. 当我将帖子保存在数据库中时,我可以存储信息,但如果用户更新了他们的信息,它就不会更新。 So I am trying to retrieve the user information from the user table at the same time as I retrieve the blog post. 所以我试图在检索博客文章的同时从用户表中检索用户信息。

How would I go about doing this with one sql query? 我将如何使用一个SQL查询来执行此操作? I know I could easily do it by just calling another query. 我知道只需调用另一个查询就可以轻松完成。

Remove , user . 删除, user It should be written this way: 它应该这样写:

SELECT blog_post.*, user.name, user.last_name, user.picture 
FROM blog_post
INNER JOIN user ON blog_post.author_id = user.id 
WHERE blog_post.author_id = ? 
ORDER BY timestamp DESC 
LIMIT 10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM