Ali insan Soyaslan
Ali insan Soyaslan

Reputation: 846

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,,

Upvotes: 0

Views: 43

Answers (1)

Koray Küpe
Koray Küpe

Reputation: 736

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.

Upvotes: 1

Related Questions