简体   繁体   English

SQL JOIN多对多

[英]SQL JOIN many-to-many

Sorry about the minimalistic title but I don't know how to describe it in short. 对简约标题感到抱歉,但我不知道如何描述它。 I have three tables: 我有三张桌子:

The table of groups 组表

ID | Genre
-----------------
1  | Action
2  | Adventure
3  | Drama

Many to many table 很多很多桌子

GroupID | ElementID
-----------------
    3   |    1
    1   |    2
    2   |    2
    2   |    3
    3   |    3

And the table of elements 和元素表

ID | Element
-----------------
1  | Pride and Prejudice
2  | Alice in Wonderland
3  | Curious Incident Of A Dog In The Night Time

All is fine and very simple. 一切都很好,非常简单。 The SELECT I am trying to achieve is the following 我想要实现的SELECT如下

ID | Element                                         |  Genre
-------------------------------------------------------------
1  | Pride and Prejudice                             | Drama
2  | Alice in Wonderland                             | NULL
3  | Curious Incident Of A Dog In The Night Time     | Drama

I want to select all the elements from the table Elements and set the genre field to Drama or null . 我想从表Elements中选择所有元素,并将类型字段设置为Dramanull

I'm trying to do this in MySQL . 我试图在MySQL中这样做。

Thank you in advance 先感谢您

It's possible with this little trick (OUTER JOIN on the many-to-many table, with the constraint that the GroupID has to be 3 (for Drama) 使用这个小技巧(在多对多表上进行OUTER JOIN,具有GroupID必须为3的约束(对于戏剧)是可能的)

http://sqlfiddle.com/#!2/b7c18/2 http://sqlfiddle.com/#!2/b7c18/2

SELECT elements.ID, elements.Element, groups.Genre
  FROM elements
LEFT OUTER JOIN group_elements
  ON elements.ID = group_elements.ElementID
 AND group_elements.GroupID = 3
LEFT OUTER JOIN groups
  ON group_elements.GroupID = groups.ID

LEFT OUTER JOIN means : take all the lines from the tables that preceded (the ones that are on the LEFT hand side of the LEFT OUTER JOIN , if you will), even if there's no lines corresponding to them in the following tables. LEFT OUTER JOIN表示:从前面的表格中取出所有行(如果愿意,可以使用LEFT OUTER JOIN左侧的那些行),即使下表中没有与它们对应的行。 The condition ON elements.ID = group_elements.ElementID AND group_elements.GroupID = 3 says that if we find anything that matches our ElementID, it also must be a drama (GroupID = 3). 条件ON elements.ID = group_elements.ElementID AND group_elements.GroupID = 3表示如果我们找到与ElementID匹配的任何内容,它也必须是戏剧(GroupID = 3)。 We then do another LEFT OUTER JOIN on the groups table, which enables us to display the Genre column, or NULL if the element was not a drama. 然后我们在groups表上执行另一个LEFT OUTER JOIN,这使我们能够显示Genre列,如果元素不是戏剧,则为NULL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM