mysql多对多关系

编程入门 行业动态 更新时间:2024-10-28 11:25:19
本文介绍了mysql多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

阅读本教程如何处理多对多与PHP和MySQL的关系.

在这个问题中,我指的是数据库架构"部分,其中规定了以下规则:

In this question I refer to the "Database schema" section which states the following rules:

此新表必须构造为 允许以下内容:

This new table must be constructed to allow the following: * It must have a column which links back to table 'A'. * It must have a column which links back to table 'B'. * It must allow no more than one row to exist for any combination of rows from table 'A' and table 'B'. * It must have a primary key.

到目前为止,一切都很清晰.

Now it's crystal clear so far.

我唯一遇到的问题是第三条规则(对于任何组合,它必须允许不超过一行的行".) 我也希望应用此方法,但似乎无法以这种方式工作.

The only problem I'm having is with the 3rd rule ("It must allow no more than one row to exist for any combination"). I want this to be applied as well, but it doesn't seem to work this way.

在mysql(5.XX)的测试实例上,我可以添加两行来反映相同的关系!

On my test instance of mysql (5.XX) I'm able to add two rows which reflect the same relationship!

例如,如果我建立此关系(通过添加一行): A到B 它还使我也可以建立这种关系: B到A

For example, if I make this relation (by adding a row): A to B It also allows me to make this relation as well: B to A

所以问题实际上是两个问题:

So the question is two questions actually:

1) 我该如何禁止执行上述第三项规则? ?无论组合如何,只有一个唯一的关系.

1) How do I enfore the 3rd rule which will not allow to do the above? Have only one unique relation regardless of the combination.

2)当我想 搜索"A"的所有关系时,SQL查询的外观如何 ?

2) When I'll want to search for all the relations of 'A', how would the SQL query look like?

注#1:基本上,我的最终目标是创建一个友谊"系统,据我所知,解决方案是一个多对多表.如果可能的话,建议其他方式.

Note #1: Basically my final goal is to create a "friendship" system, and as far as I understand the solution is a many-to-many table. Suggest otherwise if possible.

注释#2: users表与该关系位于不同的数据库中(称为友谊表)表.因此,我不能使用外键.

Note #2: The users table is on a different database from the relations (call it friendships) table. Therefore I cannot use foreign keys.

推荐答案

第一个问题:

  • 在两者上创建唯一约束 列
  • 确保始终对列进行排序.因此,如果您的桌子上有 列a和b比确保 a小于或等于 b
  • Create a unique constraint on both columns
  • Make sure you always sort the columns. So if your table has the colummns a and b than make sure that a is less than or equal to b
  • 第二个问题:

    SELECT * FROM many_to_many_table WHERE a = A or b = A

    更多推荐

    mysql多对多关系

    本文发布于:2023-10-23 13:27:22,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1520947.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:关系   mysql

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!