tags:

views:

35

answers:

2

I'm having a strange problem with MySQL and would like to see if the community has any thoughts:

I have a table 'tbl' that contains

 ____________
| id | sdate  |

And I'm trying to execute this query:

select id, max(sdate) as sd from tbl where id in(123) group by id;

This returns no results. However, this query:

select id, sdate from tbl where id in(123);

Returns many results with id's and dates.

Why would the top query fail to produce results?

+1  A: 

So IDs in this table aren't distinct, right? For example, it could be a list of questions here on StackOverflow with a viewed date, and each question ID could appear multiple times in the results. Otherwise, if the IDs are always unique then there's no point in doing a GROUP BY on them. When you're restricting the results to a single ID you don't technically need the GROUP BY clause since MAX() is an aggregate function that will return a single row.

What's the datatype of sdate? int/datetime?

It's perfectly fine to supply a single ID to an IN() clause; it just can't be blank: IN().

Is it possible to provide the output of "DESCRIBE tbl;" and a few example rows?

Jeff Standen
Correct, the ID is non-distinct. And the group by is necessary when specifying multiple items in the IN(). The data type of the columns is case_id=int and sdate=datetime.
byte
Yeah, I can't reproduce the issue you're seeing with MySQL 5.1.37. It might have something to do with the indexes on your table and when they're being used or ignored between those two queries. Can you output a "SHOW INDEXES FROM tbl"? Try "REPAIR TABLE tbl".
Jeff Standen
'tbl', 0, 'PRIMARY', 1, 'id', 'A', 3681817, , '', '', 'BTREE', '' 'tbl', 0, 'PRIMARY', 2, 'sdate', 'A', 3681817, , '', '', 'BTREE', '' 'tbl', 0, 'PRIMARY', 3, 'source', 'A', 3681817, 2, '', '', 'BTREE', ''
byte
'id', 'bigint(20)', 'NO', 'PRI', '0', '''sdate', 'datetime', 'NO', 'PRI', '0000-00-00 00:00:00', ''
byte
See my answer...
byte
Glad to hear you solved it! I'd appreciate an accept
Jeff Standen
A: 

Turns out the index was corrupt. Running the following solved the issue:

REPAIR TABLE tbl;
byte
Seemed like a possibility when I mentioned it -- since in the working case it could ignore the index. :)
Jeff Standen