简体   繁体   中英

mysql join select explained

I have two tables: 'posts' and 'users' every post has a 'ref_id' column to get the user id who posted it.

Now, I am getting posts this way:

$this->db->query("SELECT * FROM posts WHERE time > '$timeLimit' LIMIT 50");

I can't understand how to join every result to get the poster related data as well. What I am doing right now is basically a loop inside a loop, where foreach of the result, get their user info. But it is pretty obvious that this is very wrong,

Apparently I need to start using joins, but how does one do it? this should be a really simple example to work with, I suppose.

Any help? Thank you.

SELECT posts.*, users.* 
FROM posts 
INNER JOIN users 
  ON posts.posted_by = users.id;

Like this:

SELECT
  posts.*,,
  users.Username
FROM posts
INNER JOIN users ON posts.ref_id = users.user_id;

Explanation:

To JOIN to any tables with each others, there are two things; the JOIN type and the join condition. There are three main types of join:

  • INNER JOIN , only the rows that match the join condition will be returned from the two tables no more rows. But:

  • LEFT OUTER JOIN , when you join two tables you will have one on the left of the join keyword and the other one will be in the right:

    FROM Table1 <------------- This is the left table. LEFT OUTER JOIN table2 .... <------------- This is the right table.

In LEFT OUTER JOIN the unmatched rows from the left table will be included in the result set.

  • RIGHT OUTER JOIN the unmatched rows from the right table will be included in the result set.

  • CROSS JOIN this will perform a Cartesian product from the two tables.

In our query, the query will reutrn all the users from the users table only if the ref_id equal to the user_id column form the posts table.

For more information and explanations:

SELECT user.name
FROM users
INNER JOIN posts
ON posts.ref_id == user.id
AND posts.time > 50

http://www.w3schools.com/sql/sql_join_inner.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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