Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch data from multiple tables with same primary key in all tables

I have 4 tables all with the same primary key with structure like :

table_1 : u_id | col1 | col2    

table_2 : u_id | col3 | col4     

table_3 : u_id | col5 | col6    

table_4 : u_id | col7 |  col8

I want to fetch the data of "col1", "col4", "col6" and "col7" on the basis of the value of u_id.

Values of u_id are same in every table.

For eg. if u_id='8', then fetch all the specified column values where u_id='8'.

I am not using joins correctly, i guess.

Thanks.

like image 973
Mukul Kapoor Avatar asked Jan 17 '13 03:01

Mukul Kapoor


People also ask

Can the same primary key be used in multiple tables?

Every table can have (but does not have to have) a primary key. The column or columns defined as the primary key ensure uniqueness in the table; no two rows can have the same key. The primary key of one table may also help to identify records in other tables, and be part of the second table's primary key.

What is it called when two tables share the same primary key?

First when two tables have the same Primary Key and have a foreign key relationship, that means they have a one-to-one relationship.

How do I extract data from multiple tables?

In SQL, to fetch data from multiple tables, the join operator is used. The join operator adds or removes rows in the virtual table that is used by SQL server to process data before the other steps of the query consume the data.

Can we fetch data from multiple tables using one query?

To retrieve information from more than one table, you need to join those tables together. This can be done using JOIN methods, or you can use a second SELECT statement inside your main SELECT query—a subquery.


1 Answers

This should be pretty straight forward. Use INNER JOIN

SELECT  a.col1, b.col4, c.col6, d.col7
FROM    table1 a
        INNER JOIN table2 b
            ON a.u_id = b.uid
        INNER JOIN table3 c
            ON a.u_id = c.uid
        INNER JOIN table4 d
            ON a.u_id = d.uid
WHERE   a.u_ID = 8

To learn more about joins, please see the article below.

  • Visual Representation of SQL Joins
like image 175
John Woo Avatar answered Nov 15 '22 04:11

John Woo