Home > database >  How to combine two tables into one using my sql statement
How to combine two tables into one using my sql statement

Time:02-07

i'm new in Database, i want to get a result from both sql table. Here is the example

  1. Table 1
Item Code Price
A001 5 Dollar
A002 6 Dollar
  1. Table 2 - Item Code Information
Item Code Item Description
A001 Fish
A002 Chicken

And my question i want to get result with table 1 combine with 2 with item code, item description and price

Item Code Item Description Price
A001 Fish 5 Dollar
A002 Chicken 6 Dollar

Does anyone know how to do the SQL statement? Please help Thank you

CodePudding user response:

Use this codes:

SELECT T1.ItemCode,ItemDescription, Price
FROM TABLE1 T1 INNER JOIN TABLE2 T2 ON T1.ItemCode = T2.ItemCode

CodePudding user response:

Join both tables with item codes and select all the desired fields from both tables

SELECT table2.itemcode,table2.itemdescription,table1.price FROM table1 
INNER JOIN table2 
ON table1.itemcode=table2.itemcode

CodePudding user response:

Use join if you want to combine 2 or more table with sql.

SELECT Table1.itemcode, Table1.price, Table2.itemdescription FROM Table1 JOIN Tabel2 on Tabel1.itemcode = Tabel2.itemcode;

where

SELECT table_name.field_name, ... FROM table_name JOIN second_table_name on table_name.primary_key = second_table_name.foreign_key;

if you want to combine 3 then just add another join

SELECT table_name.field_name, ... FROM table_name JOIN second_table_name on table_name.primary_key = second_table_name.foreign_key JOIN third_table_name on table_name.primary_key = third_table_name.foreign_key;

CodePudding user response:

You are looking for a Join. In this case you can use a star to Retrieve ALL items of both tables:

SELECT * FROM table1 t1 JOIN table2 t2 ON t1.item code = t2.item code.

The "item_code" is primary Key in t1 and a foreign Key in t2.

On this YouTube video you can learn about table joins: https://youtu.be/0OQJDd3QqQM

CodePudding user response:

SELECT T1.ItemCode, T2.ItemDescription, T1.Price
FROM TABLE1 T1 INNER JOIN TABLE2 T2 ON T1.ItemCode = T2.ItemCode;

Here T1 is an alias for Table 1 and T2 is alias for Table2.

  •  Tags:  
  • Related