Question

I have a little mixed up!

Current user's id is stored in session.

I want to select all the users that have the same company_id of current user.

company_id is a field in user table.

The query that doesn't work:

SELECT `all_users`.`id`, `all_users`.`username`, `all_users`.`fullname`
FROM (`user` current_user)
JOIN `company` c ON `c`.`id` = `current_user`.`company_id`
JOIN `user` all_users ON `all_users`.`company_id` = `c`.`id`
WHERE `current_user`.`id` = <<<$current_user_id>>>

Error:

You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near
'current_user) JOIN `company` c ON `c`.`id` = `current_user`.`company_id` JOIN `u'
Was it helpful?

Solution

current _user is a reserved keyword in MySQL.

You need to escape it in your query to mark it as a table alias.

Use backtick in your query. Like so:

SELECT `all_users`.`id`, `all_users`.`username`, `all_users`.`fullname`
FROM `user` `current_user`
JOIN `company` c ON `c`.`id` = `current_user`.`company_id`
JOIN `user` all_users ON `all_users`.`company_id` = `c`.`id`
WHERE `current_user`.`id` = <<<$current_user_id>>>

OTHER TIPS

I think that it had a very simpler solution!

SELECT `all_users`.`id`, `all_users`.`username`, `all_users`.`fullname`
FROM (`user` u)
JOIN `user` all_users ON `u`.`company_id` = `all_users`.`company_id`
WHERE `u`.`id` = <<<$current_user_id>>>

Less join, more optimized, same result!

You should get the session user's company id to make this a lot easier on yourself and the db.

select * from all_users u left join company c on u.company_id = c.id WHERE u.company_id = current_user_id.company_id

Something like this should work just fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top