简体   繁体   中英

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)

I've attempted to use 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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