简体   繁体   English

ID匹配的MySQL查询或另一个表中有引用

[英]MySQL query where ID matches OR there is a reference in another table

I am trying to create a forum where only the creator has access to the thread. 我正在尝试创建一个论坛,只有创建者可以访问该线程。 They can then share access to other users on the forum. 然后,他们可以在论坛上与其他用户共享访问权限。 The goal is to construct a query that will pull all threads which are shared with you or that you own. 目标是构造一个查询,该查询将提取与您共享或拥有的所有线程。 I have three tables in my database 我的数据库中有三个表

  • Users (contains a list of all users) 用户(包含所有用户的列表)
  • Threads (contains all threads) 线程(包含所有线程)
  • Shared_Threads (contains a list of user ids relating to threads) Shared_Threads(包含与线程相关的用户ID列表)

I've attempted to use INNER JOIN. 我试图使用INNER JOIN。

This query only pulls tests which you own 该查询仅提取您拥有的测试

SELECT 
    `id`, 
    `content`,
    `users`.`username` as `owner`
FROM
    `threads`
INNER JOIN
    `users`
ON
    `users`.`.id` = `threads`.`owner_id`
WHERE
    `threads`.`owner_id` = ?
ORDER BY
    `threads`.`id`

I can't seem to join another table to query. 我似乎无法加入另一个表进行查询。 I need to expand the WHERE to have 我需要扩大WHERE

OR ? is in `shared_threads`

probably you need left join here. 可能您需要在这里左加入。 try this query 试试这个查询

select t.id, t.content, u.username as owner 
from threads t 
left join shared_threads st on st.thread_id = t.id
inner join users u on u.id = t.owner_id
where t.owner_id = 2 or st.user_id = 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM