Is it better to use INNER JOIN or EXISTS to find belonging to several in m2m relation?

前端 未结 4 1505
清歌不尽
清歌不尽 2021-02-18 15:03

Given m2m relation: items-categories I have three tables:

  • items,
  • categories and
  • ite
4条回答
  •  旧时难觅i
    2021-02-18 15:22

    A JOIN is more efficient, generally speaking.

    However, one thing to be aware of is that joins can produce duplicate rows in your output. For example, if item id was in category 1 and 3, the first JOIN would result in two rows for id 123. If item id 999 was in categories 1,3,7,8,12, and 66, you would get eight rows for 999 in your results (2*2*2).

    Duplicate rows are something you need to be aware of and handle. In this case, you could just use select distinct id.... Eliminating duplicates can get more complicated with a complex query, though.

提交回复
热议问题