S
S
Stanislav Fateev2015-05-26 20:54:13
MySQL
Stanislav Fateev, 2015-05-26 20:54:13

Complex query in SQL with a condition? Is it possible?

I write the following query (simplified here):

SELECT
            `name`,
            (SELECT `value` FROM `t` ORDER BY `value` DESC LIMIT 1,1) AS `second_value`,
FROM `t`;

That is, you need to get the second most value from the table `t` ordered by `value`. Sometimes this table has only one row and then SQL returns NULL, but you need to return (SELECT `value` FROM `t` ORDER BY `value` DESC LIMIT 0,1) - that is, the only value that is in the table.
Maybe I'm doing it all wrong, correct me if you can.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Ukolov, 2015-05-26
@svfat

There is a function IFNULL , you can pass two subqueries to it.
True, the solution gives some kind of curvature.

R
Rsa97, 2015-05-26
@Rsa97

SELECT `value`
    FROM (SELECT `value` FROM `t` ORDER BY `value` LIMIT 2) AS `t1`
    ORDER BY `value` DESC
    LIMIT 1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question