Question

I'm getting the first 50 records using this query. However, there is a flag named read in the same table, and I only want to return the first 50 records that are not read (i.e. isread=false). How can I achieve this? Can anybody give me ideas for the required query? I have tried using sub queries.

SELECT * FROM notification WHERE toUserId = 'email' ORDER BY id DESC LIMIT 50;
Était-ce utile?

La solution

Try adding an AND condition to your WHERE clause: userID = 'email' AND flag = true. This will only return users with true value for flag of which you can get the top 50 by your limit condition.

Autres conseils

Since you want to get the first 50 values regardless of the IsRead condition and then filter it, you can try this but I populated the query in Sql Server.

SELECT * FROM (SELECT TOP 50 * FROM notification) S WHERE toUserId = 'email' and isread=false

This should help. You can try the same technique in MySql.

SELECT * FROM notification WHERE toUserId = 'email' AND isread = 0 ORDER BY id DESC LIMIT 50;

should work, though it does depend on you using 0 for false and 1 (or anything else) for true. If you have chosen the tinyint or BOOL type then this will usually work (note tinyint can be -9 to +9 so make sure you set 0 or 1 as your flags.

In my opinion, it is probably better to use the terms 1 and 0 rather than TRUE or FALSE (though this is a matter of aesthetics really) because the code is then more readily transferrable. It also prevents lazy coding.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top