作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有三个表。一张是笔记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_name
和 last_name
的 WHERE
子句与 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/
我是一名优秀的程序员,十分优秀!