tags:

views:

63

answers:

1

I want to do this query:

  SELECT * 
    FROM mail 
   WHERE tag_draft = 0 
     AND (target_id = 2 OR source_id = 2) 
GROUP BY created DESC`

...but it returns no rows. Now, if I do this query:

  SELECT * 
    FROM mail 
   WHERE tag_draft = 0 
     AND target_id = 2 
GROUP BY created DESC

...then it works fine - every row with a target_id of 2 is selected. If I substitute target_id with source_id, it works fine too. The thing is, I want to select rows where the target OR source ID is 2 (2 used as an example here), however running the query first stated

(SELECT * FROM mail WHERE tag_draft=0 AND (target_id=2 OR source_id=2) GROUP BY created DESC)

, with or without inner brackets, returns no rows. I cannot figure out why this will not work, other than I'm doing something wrong with the OR bit.

Some example data:

source_id target_id etc_fields
-------------------------------
2         12        blah
12        2         blah
2         14        blah
2         10        blah
2         2         blah

All the above rows should be displayed in the table. what should NOT be displayed is stuff like:

source_id target_id etc_fields
-------------------------------
10        8         ...
255       16        ...
4         12        ...
+1  A: 

Here's one way, assuming there's there's not more than one row with the same MAX(created) for the given condition:

SELECT m.* FROM mail m WHERE m.tag_draft=0 AND (m.target_id=2 OR m.source_id=2) AND
  m.created = (SELECT MAX(created) FROM mail sm 
       WHERE sm.tag_draft=0 AND (sm.target_id=2 OR smsource_id=2))

Or perhaps just

 SELECT m.id,m.target_id,m,m.source_id,MAX(created) FROM mail m 
    WHERE m.tag_draft=0 AND (m.target_id=2 OR m,source_id=2) 
  GROUP BY m.id,m.target_id,m.source_id

Make sure you GROUP BY every column that you select, except the aggregate ( MAX(created) ) , SELECT * won't do.

nos
This looks promising, although I've been an idiot and not made my question clear enough :( What I have are 'threads', denoted by a thread_id column, which is the same for all rows in that thread. I also have the created date for the thread, again all the same. What is different, however, is the 'updated' field - that's unique. Would you be able to change your query to behave like I explained, or does it already?
JamWaffles
Also, what does 'm.' and 'sm.' mean? are they different tables or something?
JamWaffles
They're just aliases for the mail table. If the updated column is what you want, isn't it enough to use that column instead of the created column in the queries above ?
nos
@nos - It could be, but I want to select the most up to date post from each thread, not the entire table, if you get me?
JamWaffles
Somewhat, but this now deviates a lot from the original question. I suggest you post a new question with the actual table structures and what you want.
nos
Ok - thanks for your time/help nonetheless
JamWaffles