gpt4 book ai didi

mysql - 连接多个表以在 MySQL 中获取 NOT EQUAL 值

转载 作者:行者123 更新时间:2023-11-29 01:26:30 25 4
gpt4 key购买 nike

我已经尝试了 3 天来解决这个问题 - 现在我需要你们 :-)

我需要加入 3 个表:

table data        table user           table collection
data_id | colors user_id | user_name collection_id | user_id | data_id
---------------- ------------------- ---------------------------------
1 | blue 1 | Brian 1 | 1 | 1
2 | red 2 | Jason 2 | 2 | 3
3 | green 3 | Marie 3 | 1 | 3
4 | yellow 4 | 3 | 2

输出是用户特定的。这意味着 Brian 不想看到蓝色和绿色,Jason 不想看到绿色,而 Marie 不想看到红色。这应该给出以下输出:

for Brian           for Jason             for Marie
id | colors id | colors id | colors
----------- ----------- -----------
2 | red 1 | blue 1 | blue
4 | yellow 2 | red 3 | green
4 | yellow 4 | yellow

这是我最好的尝试(目前)如何解决这个问题:

SELECT 
*
FROM
data d
INNER JOIN
user u ON u.user_id = d.user_id
LEFT JOIN
collection c ON c.data_id = d.data_id
WHERE
c.user_id <> '1' OR c.collection_id IS NULL

结果是 Brian 的选择将得到整理 - 这很好!但是因为 Jason 也不想看到绿色,所以它仍然为 Brian 选择。相当困惑!

我希望我能写得或多或少容易理解 =)

非常感谢所有帮助和提示!

干杯

编辑:这个解决方案被这个解决方案扩展和缩短了:replace the id with the username from an other table in a CROSS JOIN in MySQL

最佳答案

可以使用交叉连接而不是在 table_collection 中

select user.id, user.name, data.data_id, data.data
from user
cross join data
where ( user.user_id, data.data_id) not in (
select user_id, data_id
from table_collection
)

关于mysql - 连接多个表以在 MySQL 中获取 NOT EQUAL 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45066407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com