gpt4 book ai didi

mysql - 如何从多个表中加入 SELECT,其中 SELECTS 基于不同的条件?

转载 作者:行者123 更新时间:2023-11-30 21:52:31 25 4
gpt4 key购买 nike

我有三个表。一张是笔记Notes,一张是用户Users,一张是用户和笔记的关系表NotesUsers

用户

user_id    first_name    last_name
1 John Smith
2 Jane Doe

注释

note_id    note_name     owner_id
1 Math 1
2 Science 1
3 English 2

注意用户

user_id    note_id   
1 1
2 1
2 2
2 3

希望您可以从 select 语句中看出我正在尝试做什么。我正在尝试选择 user_id = 2 有权访问但不一定拥有的笔记,但同时我也在尝试获取所有者的名字和姓氏。

SELECT Notes.notes_id, note_name
FROM Notes, NotesUsers
WHERE NotesUsers.note_id = Notes.note_id AND NotesUsers.user_id = 2
JOIN SELECT first_name, last_name FROM Users, Notes WHERE Notes.owner_id = Users.user_id

我的问题是因为 first_namelast_nameWHERE 子句与 notes 的子句不同,不知道怎么查询数据。我知道这不是 JOIN 的工作方式,并且我不一定要使用 JOIN,但我不确定如何构建语句,所以我将它留在那儿以便您可以理解我正在尝试做什么。

最佳答案

您可以使用 NoteUsers 加入 Notes 以检查访问权限,并使用 Users 将用户的详细信息添加到结果中:

SELECT n.noted_id, n.note_name, u.first_name, u.last_name
FROM Notes n
JOIN NoteUsers nu ON n.noted_id = nu.note_id AND nu.user_id = 2
JOIN Users u ON n.owner_id = u.user_id

关于mysql - 如何从多个表中加入 SELECT,其中 SELECTS 基于不同的条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46620873/

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