Question

This is my query:

string x1 = "SELECT unos_golub.drzava, unos_golub.spol, unos_golub.broj_goluba as broj, parovi.par_m, parovi.par_z,parovi.broj_para FROM parovi JOIN unos_golub ON (parovi.par_m=unos_golub.ID) WHERE parovi.uzgojni_par=1";
string x2 = "SELECT unos_golub.drzava, unos_golub.spol, unos_golub.broj_goluba as broj2, parovi.par_m, parovi.par_z,parovi.broj_para FROM parovi JOIN unos_golub ON (parovi.par_z=unos_golub.ID) WHERE parovi.uzgojni_par=1 ORDER BY broj_para ASC";
cmd.CommandText = x1+" UNION ALL "+x2;

In my table "parovi" there are 2 columns "par_m" and "par_z". In second table "unos_golub" there is "ID" and some other. Now I need to get values from "par_m" and "par_z", match it in "unos_golub" and get some data.

For example, if I get par_m=91 and par_z=92, I need to find those numbers in ID of "unos_golub" and get different data for 91 and 92 and show it. I think maybe UNION ALL could help, but it is not working.

here are my tables

  1. table: parovi
  2. table: unos_golub

table: parovi

table: unos_golub

Was it helpful?

Solution

This approach will put all on a single row for the respective "M" and "Z" values. Notice I'm joining TWICE to the "unos_golub" table, but with different aliases. So, now I have one parovi record pointing to respective "M" AND "Z" versions simultaneously. And can pull the columns from each, thus giving them aliased result column names suffixing "M" and "Z" indicating their respective origin.

SELECT 
      parovi.par_m, 
      parovi.par_z,
      parovi.broj_para,
      unos_M.drzava as drzava_M, 
      unos_M.spol as spol_M, 
      unos_M.broj_goluba as broj_M, 
      unos_Z.drzava as drzava_Z, 
      unos_Z.spol as spol_Z, 
      unos_Z.broj_goluba as broj_Z
   FROM 
      parovi 
         JOIN unos_golub as unos_M
            ON parovi.par_m = unos_M.ID
         JOIN unos_golub as unos_Z
            ON parovi.par_m = unos_Z.ID
   WHERE 
      parovi.uzgojni_par=1";

Per your comment of wanting to show all rows, your query SHOULD only require one small change. When doing a UNION, the queries must have the same column names. You changed one o them via

unos_golub.broj_goluba as broj
vs
unos_golub.broj_goluba as broj2

which would make it fail the query. The column names are different, thus failing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top