2

I have a destination id and I want to select other destinations, ordered first by the given destination's country followed by others. (preferably without using subquery)

destination:
- id
- name

destination_visa
- id_destination
- id_visa

visa
- id_visa
- country

How do I select the given destination's country and then order other destination based on this destination's country, preferably without using a subquery ?

SQLFiddle: http://sqlfiddle.com/#!2/31503/3

4

1 回答 1

2

Is this what you had in mind?

select
    d.id_destination, v.country, d.name 
from
    destination d
    inner join destination_visa dv on dv.id_destination = d.id_destination
    inner join visa v on dv.id_visa = v.id_visa
order by nullif (v.country, (select v2.country
                             from destination_visa dv2
                             inner join visa v2
                             on dv2.id_visa = v2.id_visa
                             where dv2.id_destination = 6));

There is still a subquery, which might be preselected into a variable.

I don't think a subquery should present a problem because it is not correlated to outer query, meaning it should be executed only once. As for order by, nulls are sorted first so I used that to nullify country matching given destination. Alternatively you might use this to make intend more clear:

order by case when v.country = (select v2.country
                                 from destination_visa dv2
                                 inner join visa v2
                                 on dv2.id_visa = v2.id_visa
                                 where dv2.id_destination = 6)
              then 0 -- Move matching country to front 
              else 1 -- Not a matching country
         end,
         v.country
于 2012-07-11T12:41:57.843 回答