简体   繁体   English

sql多对多关系只有2个表

[英]sql many to many relationship with only 2 tables

So I have two tables I need to join for a client. 因此,我需要为客户加入两个表。 These tables only share 1 field in common (COLOR, and it isn't a unique key ident). 这些表仅共享1个共同的字段(COLOR,并且它不是唯一的键标识)。 Is is possible to join/relate these two tables? 是否可以联接/关联这两个表?

So let's say theoretically I have two tables with COLOR and a COLOR ATTRIBUTE, as follows: 因此,从理论上讲,我有两个带COLOR和COLOR ATTRIBUTE的表,如下所示:

+-------+----------+
| COLOR |   NAME   |
+-------+----------+
| red   | brian    |
| red   | ben      |
| red   | tom      |
| red   | jennifer |
| blue  | tom      |
| blue  | billy    |
| blue  | michelle |
+-------+----------+  

And another table that is ONLY related by the color column, but has multiple color weights: 另一个表仅与颜色列相关,但是具有多个颜色权重:

+-------+--------+
| COLOR | WEIGHT |
+-------+--------+
| red   |     12 |
| red   |      3 |
| red   |     11 |
| blue  |      4 |
| blue  |     23 |
| blue  |      7 |
| blue  |      5 |
| blue  |     10 |
+-------+--------+  

So how can I join these two tables given ONLY the color column is shared? 那么,仅在共享颜色列的情况下,如何才能将这两个表连接起来? What would the result look like? 结果会是什么样? Thanks in advance! 提前致谢!

While color is not a unique identifier, if you plan to perform a join on it, it will be treated as such. 尽管颜色不是唯一的标识符,但是如果您打算对其进行连接,则它将被视为颜色

SELECT * FROM Table1 t1
LEFT JOIN Table2 t2
ON t1.COLOR = t2.COLOR
ORDER BY COLOR DESC;

This outputs three columns with 12 "red rows" and 15 "blue rows." 这将输出三列,其中包含12个“红色行”和15个“蓝色行”。

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

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