Is it possible to conditionally select columns in MySQL?

Mysql select with autoincrement secondary key?

  • from here: http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html I find this example: CREATE TABLE animals ( grp ENUM('fish','mammal','bird') NOT NULL, id MEDIUMINT NOT NULL AUTO_INCREMENT, name CHAR(30) NOT NULL, PRIMARY KEY (grp,id) ) ENGINE=MyISAM; INSERT INTO animals (grp,name) VALUES ('mammal','dog'),('mammal','cat'), ('bird','penguin'),('fish','lax'),('mamm... ('bird','ostrich'); SELECT * FROM animals ORDER BY grp,id; Which returns: +--------+----+---------+ | grp | id | name | +--------+----+---------+ | fish | 1 | lax | | mammal | 1 | dog | | mammal | 2 | cat | | mammal | 3 | whale | | bird | 1 | penguin | | bird | 2 | ostrich | +--------+----+---------+ -------------------- How do I select just the ones with the max ID? ie, get this result: +--------+----+---------+ | grp | id | name | +--------+----+---------+ | fish | 1 | lax | | mammal | 3 | whale | | bird | 2 | ostrich | +--------+----+---------+ I tried SELECT * FROM animals HAVING id=MAX(id) ORDER BY grp,id; but that returns the empty set. I've tried several iterations, but failed for all of them. Thanks!

  • Answer:

    I've been using mysql for over 10 years and have never come across that sort of usage of auto increment. I'm still not sure what it would be good for lol. Anyway in answer to your question: select animals.* from animals left outer join animals as animals2 on animals.grp = animals2.grp and animals2.id > animals.id where animals2.id is null; Hope this helps :)

Doug at Yahoo! Answers Visit the source

Was this solution helpful to you?

Other answers

I've been using mysql for over 10 years and have never come across that sort of usage of auto increment. I'm still not sure what it would be good for lol. Anyway in answer to your question: select animals.* from animals left outer join animals as animals2 on animals.grp = animals2.grp and animals2.id > animals.id where animals2.id is null; Hope this helps :)

Sam

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.