I have two tables

TABLE user

```
uid  | username 
----------------
1    | brandon   
2    | john   
3    | nicole

```

TABLE private\_msgs

```
id   | from  | to | message      | time
-------------------------------------------
1    | 1     | 2  | hi sister    | 100
2    | 1     | 3  | hi brother   | 300
3    | 1     | 2  | hi again!    | 400
4    | 2     | 3  | lolz message | 600

```

(column time is an actual timestamp, I just made it simple for this example)

'from' is the uid of the user

'to' is the uid of the user

I want to get the newest message from all users that were sent to a specific user

The specific user in this case is

```
$logged_id = 2;

```

The results should return the row with id=3

Query I have so far

```
SELECT private_msgs.*, users.username FROM `private_msgs`, `users` 
WHERE private_msgs.to=$logged_id AND users.uid = private_msgs.from 
INNER JOIN (
  SELECT 
    from, max(time) as latest 
  FROM private_msgs 
  GROUP BY private_msgs.from
) r ON private_msgs.time = r.latest AND private_msgs.from = r.from
ORDER BY time DESC");

```

however, I am getting the error

```
Error Number: 1064

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 'INNER JOIN ( SELECT from, max(time) as latest FROM private_msgs ' at line 3

```