How to select the row which matches a complex WHERE clause and has the minimum value in a given column?

StackOverflow https://stackoverflow.com/questions/22135081

  •  19-10-2022
  •  | 
  •  

문제

I need to select a row from a table which must satisfy the following conditions:

  • It needs to match a quite complex WHERE clause
  • It needs to have the minimum value in column X

Thus far, the only working solution I have is this:

SELECT <columns>
FROM <table>
WHERE <complex WHERE clause>
AND <columnX> = (SELECT MIN(<columnX>) FROM <table> WHERE <same WHERE clause as before>)

This strikes me as quite ugly and cumberstome, having to repeat the same (complex) WHERE clause two times.

Do you know any better way to achieve this?

도움이 되었습니까?

해결책 3

Turned out the easiest solution was ordering...

SELECT TOP 1 <columns>
FROM <table>
WHERE <complex WHERE clause>
ORDER BY <ColumnX> ASC

다른 팁

Correct me if I'm wrong, I would use a CTE (Common Table Expression) to write the complex query and have the where clause reference to it.

Hope that helps.

You could define a view or temporary table, the performance difference varying heavily on the actual problem (you could try both):

CREATE VIEW v AS
SELECT <columns>
FROM <table>
WHERE <complex WHERE clause>;

SELECT * FROM v
WHERE <columnX> = SELECT min(<columnX> FROM v);

Or even better, taking advantage of the window functions:

SELECT *
FROM (
    SELECT
        <columns>,
        MIN(<columnX>) OVER () AS minX
    FROM <table>
    WHERE <complex WHERE clause>
) t
WHERE <columnX> = minX;

http://sqlfiddle.com/#!3/0a52b/6/0

This latter should certainly read the table only once.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top