I have been working with a postgresql database with a php project, and I am just trying to construct a query. This is the scenario.
Suppose I have several tables, FOO and BAR
Table FOO looks like this:
| foo_id | foo_name | foo_data | ---------------------------------- | 1 | john | son | | 2 | jane | daughter | | 3 | sam | son | | 4 | sally | daughter |
Table BAR looks like this
| bar_id | bar_foo_id | bar_fooParent_id | bar_content | ---------------------------------- | 1 | 1 | 1 | yabba-dabba-doo | | 2 | 2 | 1 | scooby-scooby-doo | | 1 | 3 | 888 | don't have a cow, man | | 2 | 4 | 999 | d'oh! |
I can’t change the table schema, everything is as it is.
But – I can pass a value through PHP, let’s call it PARENT, that represents a value from bar_fooParent_id (so I can pass 1,2,3…657,888,999 etc).
And – foo_id in table FOO maps to bar_foo_id in table BAR.
I would like to build a SELECT Query that combines data from both tables FOO and BAR. Something like:
SELECT BAR.bar_content, (and other BAR.columns) , FOO.foo_name, FOO.foo_data
FROM FOO,BAR WHERE bar_fooParent_id=".$PARENT." AND " ...?
where ? is a little confusing.
I need to grab rows for foo_name and foo_data from table FOO based upon the selected rows from table BAR. So if a value of 1 is passed to $PARENT, then bar_fooParent_id would be 1, I would get the first two rows from table BAR, and use their respective bar_foo_ids (with values 1 and 2) to grab the data from the rows of table FOO that have foo_ids of 1 and 2 (the first two rows in this case).
I have tried statements similar to those below (values are hard coded for simplicity)
SELECT * from BAR,FOO where BAR.bar_fooParent_id=1 AND (BAR.foo_id=1 OR BAR.foo_id=2) AND (FOO.foo_id=1 OR FOO.foo_id=3)
OR
select * from BAR where BAR.barr_fooParent_id=1 IN (SELECT foo_id,foo_name from kid WHERE foo_id=1 OR foo_id=3 )
without much success. Basically the data should return ideally as
foo_name | foo_data | bar_content | other BAR columns ... | _________________________________________________________________ john | son | yabba-dabba-do | etc. | jane | daughter | scooby-dooby-do| etc. |
(apologies for the formatting, not sure what is happening with this third table of results)
I’d appreciate it if someone can lend a hand in building this SELECT query for postgreSQL.
any ideas? and thanks.
Edward
Sounds like all you need is a simple join: