Eemil Laine
Eemil Laine

Reputation: 21

LEFT JOIN cant get it right

My problem on getting one row shown with two null values.

My tables are shown below

FROM tuote;
     ttunnus |         tnimi         |       kuvaus       | suositushinta | tmtunnus
    ---------+-----------------------+--------------------+---------------+----------
         111 | Trimmeri TRCee        | tehokas 4-tahtinen |        179.00 |        1
         112 | Trimmerisiima Cee     | laadukas siima     |          6.99 |        1
         113 | Moottorisaha MSCee RR | robusti ja raskas  |        559.00 |        1
         114 | Trimmerisiima Y       | yleissiima         |          3.99 |        2
         115 | Lapio L               | kevyt yleislapio   |         23.95 |        2
    (5 rows)

FROM kategoria;
 ktunnus |   knimi
---------+-----------
      11 | puutarha
      14 | valaistus
      12 | metsä
      13 | lumityöt
(4 rows)

FROM tuote_kategoria;
 ttunnus | ktunnus
---------+---------
     111 |      11
     112 |      11
     113 |      11
     113 |      12
     114 |      11
     115 |      11
     115 |      13
(7 rows)

I need to get this information from tables with valaistus ON NULL values in tnimi and suositushinta

   knimi   |         tnimi         | suositushinta
-----------+-----------------------+---------------
 puutarha  | Trimmeri TRCee        |        179.00
 puutarha  | Trimmerisiima Cee     |          6.99
 puutarha  | Moottorisaha MSCee RR |        559.00
 metsä     | Moottorisaha MSCee RR |        559.00
 puutarha  | Trimmerisiima Y       |          3.99
 puutarha  | Lapio L               |         23.95
 lumityöt  | Lapio L               |         23.95
 valaistus |                       |
(8 rows)

but i only get it like this not in the right way.

SELECT t2.knimi, t1.tnimi, t1.suositushinta
    FROM tuote t1, tuote_kategoria
    LEFT JOIN kategoria t2 ON t2.ktunnus = tuote_kategoria.ktunnus
    WHERE t1.ttunnus = tuote_kategoria.ttunnus;
      knimi   |         tnimi         | suositushinta
    ----------+-----------------------+---------------
     puutarha | Trimmeri TRCee        |        179.00
     puutarha | Trimmerisiima Cee     |          6.99
     puutarha | Moottorisaha MSCee RR |        559.00
     metsä    | Moottorisaha MSCee RR |        559.00
     puutarha | Trimmerisiima Y       |          3.99
     puutarha | Lapio L               |         23.95
     lumityöt | Lapio L               |         23.95
    (7 rows)

Upvotes: 0

Views: 37

Answers (1)

Thorsten Kettner
Thorsten Kettner

Reputation: 94939

You want to show kategoria records, even when they don't have a match in the other tables. So select from kategoria and outer join the other two tables:

select
  k.knimi,
  t.tnimi,
  t.suositushinta
from kategoria k
left join tuote_kategoria tk on tk.ktunnus = k.ktunnus
left join tuote t on t.ttunnus = tk.ttunnus;

Upvotes: 1

Related Questions