views:

58

answers:

1
+1  Q: 

mysql query help?

I have a table with
'id' as the primary field and set to auto increment..
'name' of type varchar ..
'category' of type varchar ..

Table contents ::.
* id=1,name=abc,category=tv
* id=2,name=abc,category=radio
* id=3,name=abc,category=tv
* id=4,name=abc,category=radio
* id=5,name=abc,category=tv
* id=6,name=abc,category=tv


Now, I want to select latest rows where category="tv" i.e row 5, row 6 only
This is just an example the real table might have many categories, I hope I am clear in the way I am putting forward my issue...
Please help....

from the answers given ...this query is showing results how i want them ::.

SELECT * FROM test WHERE id > (SELECT id FROM test WHERE category !="tv" ORDER BY id DESC LIMIT 1)

but when i add 1 more row to my table the query shown no results which i can understand why..
$$$$I want the final block of a particular category $$$$

+2  A: 

I think this is what you need.

SELECT * FROM table
    WHERE id >
        (SELECT id FROM table
            WHERE category !=
                (SELECT category FROM table
                    ORDER BY id DESC LIMIT 1)
            ORDER BY id DESC LIMIT 1);

The inner most SELECT is finding the category of the last category block. The middle select is finding the ID of the last row that's a different category than that. Then the outer select is selecting all rows after that id. So, it will find all the rows that are part of the final category block.

EDIT:

SELECT * FROM table
    WHERE category = 'radio' && id >
        (SELECT id FROM table
            WHERE category != 'radio' && id <
                (SELECT id FROM table WHERE category = 'radio' ORDER BY id DESC LIMIT 1)
            ORDER BY id DESC LIMIT 1)

I think that should do what you need. Notice that there are 3 places you need to put in the category you're looking for (in this example it's looking for 'radio').

Cahlroisse
I want to select the final block of category ='tv' or a particular category that has been added to the database
halocursed
You mean a specific category and not the last category?
Cahlroisse
yes!!!! There could be many blocks of a particular category and I want the final block i.e if <br>* id=1,name=abc,category=tv<br>* id=2,name=abc,category=radio<br>* id=3,name=abc,category=tv<br>* id=4,name=abc,category=radio<br>* id=5,name=abc,category=tv<br>* id=6,name=abc,category=tv<br>* id=7,name=abc,category=radio<br>i want row 5 and row 6 only if i am requesting for category='tv'
halocursed
Okay. I added an edit version that I think may be what you need.
Cahlroisse
Thanks a lot man....Exactly what I needed ..Thanks for taking out the time for helping...
halocursed