Reputation: 161
I have two tables:- PERSON
and DATA
. What I want to do is fetch all details from PERSON
table and only two columns from DATA
table only when PERSON.personId = DATA.personId
.
I am using this query:-
SELECT *
FROM PERSON AND SELECT DATA.value, DATA.field
FROM DATA where PERSON.personId = DATA.personId;
But I think this is wrong syntax. Can anyone tell me what is the right syntax for it.
Upvotes: 1
Views: 6948
Reputation: 152
Here's the correct syntax for achieving what you've asked for:
SELECT PERSON.column1,PERSON.column2,PERSON.columnN,DATA.value
FROM PERSON
INNER JOIN DATA
ON PERSON.personId = DATA.personId
Upvotes: 0
Reputation: 1238
Its really easy, Just execute this query:
SELECT
PERSON.*,
DATA.value,
DATA.field
FROM
PERSON INNER JOIN DATA USING (`personId`);
It selects all fields of PERSON + value and field from DATA. Also it uses personId to join the two tables.
Fill free to ask if you need more info.
Upvotes: 1
Reputation: 1109
SELECT p.*,d.column1,d.column2
FROM Person p
JOIN Data d
ON p.personId = d.personId
WHERE <Condition>
In this query person with all columns and data with your desire column you can fetch by this query.
Upvotes: 3
Reputation: 4266
You can use join (LEFT JOIN)
SELECT * FROM PERSON LEFT JOIN DATA ON PERSON.personId = DATA.personId
Hope it will help you
Upvotes: 0
Reputation: 2044
Something like this:
select
P.*,
D.value,
D.field
from Person P
join Data D on P.PersonID = D.PersonID
change P.* to the specific columns that you need but P.* will get everything from the Person table.
check this post out LEFT JOIN vs. LEFT OUTER JOIN in SQL Server to learn about JOINS
, the diagram is good to understand what the different ones do
Upvotes: 2