简体   繁体   中英

MySql Join more than 2 tables?

I have the following 3 tables and want to get into the "inventory" table where user_id = user_id and want to show all "ownedskins" from a user with this id.

How can I do this?

Thanks for all replys!

The three tables

Joining more than 2 tables with MySql example:

SELECT    i.*
FROM      ownedskins o
          JOIN inventory i
              ON o.inventory_id=i.inventory_id
          JOIN user u
              ON u.user_id = i.user_id
WHERE     u.user_id = 1

Using joins is very easy, use something like this:

SELECT *
FROM table1 t1
JOIN table2 t2 ON t1.id = t2.id
JOIN table3 t3 ON t2.id2 = t3.id

You can also use JOIN variants like LEFT JOIN, INNER JOIN, OUTER JOIN...

Let's say you have the following tables:

Driver
Car
Keys

If you want access to all 3 of them you could do the following:

SELECT D.name, C.plate, K.state
FROM Driver D, Car C, Keys K
WHERE C.key_id = K.id and
      K.owner_id = D.id;

Using JOINS:

SELECT    D.name, C.plate, K.state
FROM      Car C JOIN Keys K
              ON C.key_id = K.id JOIN Driver D
                  ON K.owner_id = D.id;

Given that you know the user_id , you could do that with a single join , like this:

SELECT
  ownedskins.*
FROM
  ownedskins JOIN inventory ON ownedskins.inventory_id = inventory.inventory_id
WHERE
  inventory.user_id = x

Where x is the id of the user you want

You can also do it with alias to make it look cleaner:

SELECT
  os.*
FROM
  ownedskins os JOIN inventory i ON os.inventory_id = i.inventory_id
WHERE
  i.user_id = x

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