I’ve been trying to get this complex MYSQL query to work exactly right over the last few days, of course because it’s got so many aspects to it that effect it it’s difficult to surely know that it’s 100% working correctly, and I’m not at all good with more complex MYSQL queries. also this query that I have now is quite messy, so the data it returns is a little scattered, and I’m not exactly sure how to address this issue. I’ve read through MYSQL Join and everything and I sort of understand it, but I’m not sure which to use in my case, and how to use them properly.
Here’s my current query that works as it should. (just needs cleaning up, I think, so I don’t have to have redundant values)
$notificationsq = mysql_query("SELECT
N.*,
N.fromID,
N.date,
N.id AS ID, //I have to do this because if I don't it doesn't return anything,
///I guess because it joins 3 tables with the id column. not sure
///how to call the correct data.
MIN(N.state) AS State,
MAX(N.date) AS newDate,
P.*,
C.*,
P.id AS uniqueID
FROM notifications N
LEFT JOIN comments C ON N.action = 2 AND N.uniqueID = C.id AND C.state=0
LEFT JOIN posts P ON N.action = 1 AND P.id = N.uniqueID
OR N.action = 2 AND P.id = C.postID
WHERE N.userID = '$session'
AND (N.action = 1 AND N.state IN (0, 1) OR N.action = 2)
AND P.state = 0
GROUP BY P.id
ORDER BY
State ASC,
newDate DESC
") or die(mysql_error());
My table structure:
Table: notifications
id UserID FromID UniqueID Action State Read_Date Date
1 1 2 1 1 0 0 1325993600
2 1 6 2 1 0 0 1325993615
3 1 2 1 2 0 0 1325993622
4 1 6 2 2 0 0 1325993661
5 2 6 2 2 0 0 1325993661
Action = 1 means UniqueID identifies a column in Posts;
Action = 2 means UniqueID identifies a column in Comments.
Table: posts
id ToID FromID Post State Date
1 1 2 Hey 0 1325993600
2 1 6 okay yeah 0 1325993615
Table: comments
ID PostID FromID Comment State Date
1 1 2 lol 0 1325993622
2 1 6 ohh 0 1325993661
So, in the Notifications table where action is 2, the UniqueID’s are for the ‘id’ in the Comments table.
What I want to return is the PostID, so in the query it would just be as if the UniqueID was this instead:
1
2
1
1
1
If your state = 0 filter limits the connection to the comments, then the inner join on the posts could filter out the result, try making that a left join as well to test.
You should have a prefix on your ORDER BY clause (either ORDER BY P.State or N.State).
The reason you’re having an error with the N.id is that the id is already selected with the N.*
You’re better to use an ENUM type to deal with multiple states. This leads to more readable SQL with the same performance (ie. N.action = ‘add’, instead of 2)
Avoid any select *, it’s error prone and the performance isn’t as good as the manual alternative.
As far as cleaning up, I find it much easier to read with clean whitespace and names: