Question

OK, so this might sound complicated, let me explain... i've been banging my head on this for a while, and i'm stuck in a loop now... can't figure it out!

T1 is a simple alert data table. It's got theses headers :

|   ID   |   TITLE   |   DATA   |
---------------------------------
|   1   |    Title1  |  Text1   |
|   2   |    Title2  |  Text2   |

T2, is just a simple user table

|   ID   |  Name  |
-------------------
|   1    |  Fred  |
|   2    |  Bill  |
|   3    |  Brad  |

T3 is a link table between T1 and T2. Basically, the first time a user (T2.ID) views an alert (T1.ID) he hasn't viewed, his ID is added to this table so I know he's viewed it.

|   ID   |  T1ID |  T2ID |
--------------------------
|   1    |   1   |   1   |
|   2    |   1   |   2   |
|   3    |   1   |   3   |
|   4    |   2   |   2   |
|   5    |   2   |   3   |
|   6    |   3   |   1   |
|   7    |   3   |   3   |

I can tell user 1 has not viewed alert 2 nor has user 2 viewed alert 3. So next time they login, I should popup these alerts to them... So if i'm user 1, when I login my admin site, I want MySQL to tell me I havn't viewed alert 2, then UPDATE that table when I do.

As I sayed, T3 should build up everytime a user views an alert where his ID does not match an alert ID. I feel, i'm so damn close...

Simple enough, now how do I do it? I ain't going to post what doesn't work...

Please help...

Was it helpful?

Solution

The first thing, you want to start with the alert table as it is applicable to all uers. From there, doing a LEFT-JOIN to the already viewed table specifically for the login user ID in question AND the alert IDs are the same.

The where clause is looking ONLY for those entries that it CAN NOT find the corresponding login user ID as having viewed the alert. For those, get the alert's title and data. After that, and presentation to the user, you can insert after the alerts have been viewed.

I would ensure the already viewed table has an index on both keys (T1ID, T2ID) to help optimize the join

SELECT
      T1.Title,
      T1.Data
   from
      YourAlertTable T1
         LEFT JOIN AlreadyViewedTable T3
            ON T3.T2ID = TheUserIDParameterWhoLoggedIn
            AND T1.ID = T3.T1ID
   where
      T3.T2ID IS NULL

OTHER TIPS

try :

Select * from t1 where id  not in (select t3.t1id from t3 where t3.t2id = <loggedin userid>)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top