我目前正在从事一个涉及多对多和一对多关系的非常大的项目......有几个表可以使用,但我不知道如何做我想做的事. 这是我的第一个表(对象表):
+-----------+------+-------+
| Object ID | Name | Value |
+-----------+------+-------+ The Object ID is a foreign Key to another table.
| 1 | Aaaa | 2 | The Name is unique for each Object ID.
| 1 | Bbbb | 5 |
| 2 | Aaaa | 15 |
| 2 | Bbbb | 3 |
+-----------+------+-------+
我的第二个表如下(用户表):
+---------+------+-------+
| User ID | Name | Value |
+---------+------+-------+ The User ID is also a foreign Key, there are
| 7 | Aaaa | 10 | multiple rows with the same User ID.
| 7 | Bbbb | 7 |
+---------+------+-------+
我有第三个表显示其他表之间的关系
+---------+-----------+
| User ID | Object ID |
+---------+-----------+ There are no identical rows in this table.
| 7 | 1 |
+---------+-----------+
我试图在对象表中找到用户拥有的所有对象。用户需要拥有所有对象名称。对于每个名称,用户的值必须至少是该名称的对象的值。
例如,用户的 Aaaa 值为 10,Bbbb 值为 7。因此他拥有对象 1 的所有名称,并且他的值大于或等于这些值。 因此他可以拥有第一个对象。 对于对象 2,User 没有足够的 Aaaa,所以他不能拥有对象 2。
我知道如何获取 Objects Table 的所有行,其中 User 具有 Name 并且具有足够大的值与 Inner Joins :
SELECT Users.User ID, Objects.Object, Objects.Name ID FROM Objects
INNER JOIN Users
ON Objects.Name = Users.Name AND Objects.Value <= Users.Value
但问题是它会返回以下内容:
+---------+-----------+------+
| User ID | Object ID | Name |
+---------+-----------+------+
| 7 | 1 | Aaaa |
| 7 | 1 | Bbbb |
| 7 | 2 | Bbbb |
+---------+-----------+------+
问题是我想去掉这里的最后一行,因为用户没有足够的 Aaaa 用于对象 2。
任何帮助将不胜感激! 谢谢
最佳答案
您可以使用 not exists
子句来要求没有匹配对象的值高于用户值:
select Users.User ID, Objects.Object, Objects.Name ID
from Objects o
join Users u
on o.Name = u.Name
where not exists
(
select *
from Objects o2
where o2.Name = u.Name
and o2.Value > u.Value
)
关于mysql - SQL 查询中的复杂条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10773477/