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.
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.
First when two tables have the same Primary Key and have a foreign key relationship, that means they have a one-to-one relationship.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With