Turned out the easiest solution was ordering...
SELECT TOP 1 <columns>
FROM <table>
WHERE <complex WHERE clause>
ORDER BY <ColumnX> ASC
Вопрос
I need to select a row from a table which must satisfy the following conditions:
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.