Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i select data across two tables using SQL where a field from each table matches?

Tags:

sql

oracle

Delphi 2010 & Oracle Database

I need to write a select statement across two tables

Accounts & Master

From the Accounts table, I need to select the Account_Id, Account_Number, Bank_Id, and External_Code

From the Master table, i need to select the Account_String.

The Master's Account_String field matches the Account's Extenal_Code field

thanx

like image 224
Shane Avatar asked Dec 29 '11 21:12

Shane


People also ask

How can I match data from two tables in SQL?

(INNER) JOIN : Returns records that have matching values in both tables. LEFT (OUTER) JOIN : Returns all records from the left table, and the matched records from the right table. RIGHT (OUTER) JOIN : Returns all records from the right table, and the matched records from the left table.

How do you find the common field between two tables?

The only way is to go to each table and manullay check for the field names and data. Almost all the field names will be same if they are present in diff tables. After detemining the common fields u can go for an Inner join statement to get the required data. Exactly which tables u need to compare.

Can a query include fields from multiple tables?

Double-click the two tables that contain the data you want to include in your query and also the junction table that links them, and then click Close. All three tables appear in the query design workspace, joined on the appropriate fields. Double-click each of the fields that you want to use in your query results.

Which command is used to match values from two tables in SQL?

UNION allows us to compare two same types of tables or datasets. We can use union to compare the columns once we can have the union of both the tables. It can quickly check what are the data missing or changed in either table. It is capable of handling null values which cannot be handled by where clause.


2 Answers

Sounds like a simple join, unless I'm missing something:

SELECT a.Account_Id, a.Account_Number, a.Bank_Id, a.External_Code, m.Account_String 
FROM Accounts a
INNER JOIN Master m ON m.Account_String = a.External_Code
like image 162
Eric Petroelje Avatar answered Oct 31 '22 07:10

Eric Petroelje


Standard SQL:

select Accounts.Account_id, Accounts.Account_Number, Accounts.Bank_Id,
    Accounts.External_Code, Master.Account_String  
from Accounts, Master
where Accounts.External_Code = Master.Account_String;

Note: You probably don't need both Accounts.External_Code and Master.Account_String in the result, as the query guarantees they are the same.

like image 32
Scott Hunter Avatar answered Oct 31 '22 09:10

Scott Hunter