I have two tables:
Table A:
| id | type | name
| 1 | Person | Fred
| 2 | Animal | Rover
| 3 | Animal | Snowball
| 4 | Person | Mary
Table B:
| id | city
| 1 | NYC
| 4 | Charlotte
What I want:
| id | type | name | city
| 1 | Person | Fred | NYC
| 2 | Animal | Rover | NULL
| 3 | Animal | Snowball | NULL
| 4 | Person | Mary | Charlotte
In other words, Table A is a table of People and Animals. Table B is a table of the cities people live in. I would like to (In a single query, if possible) get every result from Table A and, if it’s a person, get that person’s city in Table B. Is that possible in a single query? If not, what is the fastest way?
I’ve tried to do a simple join (e.g. “SELECT * FROM tableA,tableB WHERE tableA.id==tableB.id”), but doing that only gets the results of the people and not the animals.
thx!
Use
LEFT JOINon thisSQLFiddle Demo
and assuming that only person has records on
tableB