lundi 25 avril 2016

PostgreSQL - SQL : Select from table with conditional column from another table

Here is the problem,

I have "related tables" like TOWN and STREET. Street has a foreign key that corresponds to the town id.

Table structure could be like this :

TOWN :

id (pk) || name

STREET :

id (pk) || name || town (fk)

What I'd like to get, is a request that gives me back all the towns, and adds a column when the table has streets registered into it!

Let's imagine TOWN-A has no streets registered. And TOWN-B has 2 streets registered. Result from my query can be :

[{"id":"1","name":"TOWN-A"},{"id":"2","name":"TOWN-B","hasStreets":"2"}]

or

[{"id":"1","name":"TOWN-A","hasStreets":NULL},{"id":"2","name":"TOWN-B","hasStreets":"2"}]

Thanks for reading/help

Aucun commentaire:

Enregistrer un commentaire