简体   繁体   中英

JOIN TABLES with multiple columns using Query in Mysql

I need to join tables but couldn't really understand what is on the websites. Could you help me?

I have the tables

Products

ID / product_name / product_description / product_code /

Users

ID / username / username_id / password /

Checkedout

ID /product_name /product_des /username /username_id /checkedout_date / return_date /

How can I join from Products (product_name / product_description ) and from Users (username / username_id) to Checkedout ?

Thanks very much.

Joining tables is fairly simple. I'll leave it to you to continue your learning, but here is how you join those tables, so that you have a reference to better understand what you're learning.

The idea is that you just have to list your tables (in this case, I've added arbitrary aliases to each table - c , p , and u ), and specify whether you want an inner or outer join, and then specify which columns to join on . You join on columns that have the same value in both tables. For example, Checkedout has a username_id and the Users table has an ID. You can use all the same logic you would use in a WHERE clause when specifying what to join on (including AND and OR)

select
    *
from
    Checkedout c
    inner join Products p
        on (c.product_name = p.product_name and c.product_des = p.product_description)
    inner join Users u
        on (c.username_id = u.ID)

First you need to update your database schema so that the tables are normalized. Suggested schema for Checkedout :

Checkedout - id, product_id, user_id, checkedout_date, return_date

Now you can write a join query very easily(something like this):

select u.username, p.product_name, co.checkedout_date from Checkedout as co join Users u on u.id = co.user_id join Products p on p.id = co.product_id where u.id = 1;

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