简体   繁体   中英

mysql join with extra conditions

I am running this query in a php script. I have a paper and user tables. If every paper has a owner user. And every user has a company id. What I want is users who have same company id should see each others papers,so I tried to check this permission via paper_id and user_id.

papers
---------
id
user_id
paper_details


users
----------
user_id
company_id
user_details

To check is there a result exists for a paper and a user I tried query below. I only have $user_id_variable and $paper_id_variable variables while making this query. However I could not fit ** $user_id_variable** in any place in query.

SELECT * FROM papers
INNER JOIN
users u on u.user_id= papers.user_id
WHERE
papers.user_id in (
  SELECT user_id FROM users WHERE users.company_id=u.company_id
)
AND papers.id = '$paper_id_variable'

EDIT Sample data and expected result:

--papers--
 id | user_id
 1  | 1


--users--
user_id | company_id
  1     | 10
  2     | 10
  3     |  11 

According to table above expected results should be :

when paper id = 1 and user id 1 -> result count  = 1
when paper id = 1 and user id 2 -> result count  = 1
when paper id = 1 and user id 3 -> result count  = 0

Thanks for your time,,

You can use this query:

SELECT *
FROM papers
INNER JOIN users u on u.user_id=papers.user_id
WHERE u.company_id = (SELECT company_id FROM users WHERE user_id = '$user_id_variable')
AND papers.paper_id = '$paper_id_variable'

Note: Saving company_id in your papers table may be another idea. Don't forget to create indexes and don't use field names like user_id, paper_id . Just use id . Same for your PHP variable, use $paperId instead of $paper_id_variable . They are not a must but good practices.

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