I have two tables, Customer
table and a lookup table which in customer table has 3 columns and lookup table has 2 columns (which is like vlookup in Excel). Every detailed information is in the lookup table. I want to get detailed information match with customer table.
Customer
table:
Custo ID | name | address |
---|---|---|
1 | 1 | 6 |
2 | 4 | 6 |
3 | 4 | 7 |
4 | 3 | 8 |
5 | 2 | 7 |
Lookup
table:
lk_id | lk_value |
---|---|
1 | A |
2 | B |
3 | C |
4 | D |
5 | E |
6 | x |
7 | y |
8 | z |
How can I get the output like this:
name | address |
---|---|
A | x |
C | z |
I tried this query
Select
name, address
from
customer, lookup
where
lk_id = name
and lk_id = address
But I am getting only first column in where condition, how can I get address column?
2
Answers
You can use two joins, one on the name and one on the address
The issue with your query is that you are not properly handling the two separate joins between the
Customer
table and theLookup
table. To match both thename
andaddress
columns with theLookup
table, you need to join theLookup
table twice: once for thename
column and once for theaddress
column.Here is the corrected query:
Explanation:
Alias usage:
lookup_name
is an alias for theLookup
table when joining it for thename
column.lookup_address
is an alias for theLookup
table when joining it for theaddress
column.Joins:
JOIN
matches thename
column fromCustomer
withlk_id
inLookup
.JOIN
matches theaddress
column fromCustomer
withlk_id
inLookup
.Column Selection: The query selects the
lk_value
from each join to get the desired details for bothname
andaddress
.Output:
Based on your example data, this query will return: