开发者

Joins on MySQL many-to-many tables

开发者 https://www.devze.com 2023-03-29 22:21 出处:网络
This has been driving me mad. I have three tables: items ID name type cats ID name items_to_cats FK_ITEM_ID FK_CAT_ID

This has been driving me mad.

I have three tables:

items
  ID
  name
  type

cats
  ID
  name

items_to_cats
  FK_ITEM_ID
  FK_CAT_ID

This is a simple many-to-many relationship. I have items and categories. Each item can be linked to one or more categories. This is done via a simple joining table where each row maintains a relationship between one item and one category using foreign key constraints.

You will notice that my "items" table has a field called "type". This is an indexed column that defines the type of content stored there. Example values h开发者_如何转开发ere are "report", "interview", "opinion", etc.

Here's the question. I want to retrieve a list of categories that have at least one item of type "report".

Ideally I want to get the result in a single query using joins. Help!


select distinct cats.id, cats.name
from cats
join items_to_cats on items_to_cats.fk_cat_id=cats.id
join items on items.id=items_to_cats.fk_item_id
where items.type='report'

Just as a point of database design, if you have a small set of legal values for items.type, i.e. "report", "interview", "opinion", maybe a couple more, then you really should create a separate table for that with, say, an id and a name, then just put the type id in the items table. That way you don't get into trouble because somewhere it's mis-spelled "raport", or even more likely, someone puts "reports" instead of "report".


or how about this :

SELECT c.id, c.name 
FROM cats c
WHERE c.id IN 
    (SELECT ic.fk_cat_id 
     FROM items_to_cats ic 
     JOIN items i on i.id=ic.fk_item_id 
     WHERE items.type='report'
    )
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号