Question

I am using vfp9.

I have two tables:

Countries with the field:
id
--
1
2
3

Students with the fields:
id  nname  nation1id   nation2id   nation3id
--------------------------------------------
1   A         2            1  
2   B         1
3   C         2            3          1

I want a query with this output:
countryid    nname   dummy
--------------------------
1             B        1
1             A        2
1             C        3
2             A        1
2             C        1
3             C        2

In other words, for country with id 1 I want to list the people who has it as nation1id first, then those who has it as nation2id, and last those who has it as nation3id. Then I will do the same for country with id 2, and so on.

I have tried this query:

 select countries.id from countries ;
 (SELECT nname, 1 FROM students WHERE nation1id = countries.id ;
 UNION ;
 select nname, 2 FROM students WHERE nation2id = countries.id ;
 UNION ;
 select nname, 3 FROM students WHERE nation3id = countries.id ;
 order by 2)

but get "Command contains unrecognized phrase/keyword" error message.

Regards,

Jan Nordgreen

No correct solution

OTHER TIPS

missing your country table columns, but the failure is because you have two tables listed... your countries, and your (select/union), but no comma between them or JOIN condition. As for your countries table not listing fields, I'm sure you are looking for the nation's name, but have "nname" in the student's table and don't know if that is correct or not from my perception. Anyhow, you could get the output of your query as below.

select ;
      allStNat.Nation as CountryID,;
      allStNat.nname,;
      allStNat.NationSort ;
   from ;
      ( SELECT nname, ;
               nation1id as Nation, ;
               1 as NationSort;
           FROM students ;
          WHERE nation1id > 0;
        UNION ALL;
        select nname, ;
               nation2id as Nation,;
               2 as NationSort;
           FROM students ;
          WHERE nation2id > 0;
        UNION ALL;
        select nname, ;
               nation3id as Nation,;
               3 as NationSort ;
           FROM students ;
          WHERE nation3id > 0 ) allStNat;
   order by ;
      1, 3, 2

If there was other content from the countries table you wanted, I would alter only slightly by adding the actual country's name and adjusting the order by clause since there is an additional column in the list.

select ;
      allStNat.Nation as CountryID,;
      c.Country,;
      allStNat.nname,;
      allStNat.NationSort ;
   from ;
      ( same select/union query above ) allStNat;
         JOIN Countries c ;
            ON allStNat.Nation = c.id
   order by ;
      1, 4, 3
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top