JakeParis
JakeParis

Reputation: 11210

Select all values from table B where matches table A

I have this schema:

items               | taxonomy             |    subjects 
                    |                      |
ID    headline      | item_id  subject_id  |    subject_id    subject
-------------------------------------------------------------------------
1     information   | 1        1           |    1             cities
2     here we are   | 2        1           |    2             towns
3     more things   | 3        2           |    3             water 
4     doo dah       | 3        4           |    4             telephones
                    | 4        1           |
                    | 4        3           |

I would like to select a single row from "items" and with it, include all the rows from "subjects" which are joined by the "taxonomy" table. So for example, getting item.ID=3 would result in something like:

items.ID         = 3
items.headline   = "more things"
subjects.subject = "towns"
subjects.subject = "telephones"

I've started with this query

 SELECT 
    i.ID,
    i.headline,
    s.subject_name
  FROM items i
  JOIN taxonomy t 
    on i.ID=t.item_id 
  JOIN subjects s 
    on t.subject_id=s.subject_id  
  WHERE i.ID = 3

But this only returns a single value from subject_name even if there are multiple values associated with that item_id.

EDIT I actually had a LIMIT 1 on the query which was causing (as @Gordon Linoff said) only one row to be returned, even though there were multiple rows in the result set corresponding to the multiple subjects. His solution still does nicely, because I only want to return a single row.

Upvotes: 1

Views: 90

Answers (2)

fabrosell
fabrosell

Reputation: 614

I would suggest you the "union all" clause (or "union", if you are not needing the duplicates).

 (SELECT 
    "taxonomy" As Name,
    i.headline As Value
  FROM items i
  JOIN taxonomy t 
    on i.ID=t.item_id 
  WHERE i.ID = 3)

Union All

 (SELECT 
    "subject" As Name,
    s.subject_name As Value
  FROM items i
  JOIN subjects s 
    on t.subject_id=s.subject_id  
  WHERE i.ID = 3)

You can add a 2nd field in each select to indicate type of item selected ("headline", "subjects", etc).

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1269503

Your query returns the subjects on multiple rows. If you want the subjects on a single row, then you need some form of concatenation:

 SELECT i.ID, i.headline, GROUP_CONCAT(s.subject_name) as subjects
 FROM items i JOIN
      taxonomy t 
      ON i.ID = t.item_id JOIN
      subjects s 
      ON t.subject_id = s.subject_id  
 WHERE i.ID = 3
 GROUP BY i.ID, i.headline;

For one item, the GROUP BY is optional, but it is good form in case you modify the query to handle multiple items.

Upvotes: 3

Related Questions