Databáze > Firebird a Interbase
Pomoc s SQL
(1/1)
Stanislav Hruška:
Mám tabuľku
--- Kód: ---CREATE TABLE MATCHES
(
MATCHID PRIMARYKEY,
ROUNDFK FOREINGKEYNULL,
STADIUMFK FOREINGKEYNULL,
TEAM1FK FOREINGKEY,
TEAM2FK FOREINGKEY,
INTABLE BOOL,
DATES DATES,
GROUPNR INT_VAL,
REMATCH BOOL,
WINNER INT_VAL,
VISITORS INT_VAL,
NOTE MEMO500,
GOAL1 INT_VAL DEFAULT 0 NOT NULL,
GOAL2 INT_VAL DEFAULT 0 NOT NULL,
WINNERTEAM FOREINGKEYNULL,
TAG INT_VAL,...
--- Konec kódu ---
Potrebujem k TEAM1FK A TEAM2FK dostať aktuálne názvy/skratky. Pre jeden Team to nie je problém. Akonáhle to urobím pre oba tými, tak dopyt trvá 1 min a viac. Je jedno či použijem WITH, VIEW alebo akúkoľvek inú techniku.
--- Kód: ---WITH
TN1 AS (SELECT MAX(N.DATEFROM) AS DATEFROM, N.TEAMFK, N.TEAMNAMEID
FROM TEAM_NAMES N
WHERE N.TEAMFK > 0 AND EXTRACT(YEAR FROM N.DATEFROM) <= 2006 AND ((EXTRACT(YEAR FROM N.DATETO) >= 2006) OR
(N.DATETO IS NULL))
GROUP BY N.TEAMFK, N.TEAMNAMEID)
SELECT N1.ACRONYM AS TITLE2, N2.ACRONYM, M.GOAL2, M.GOAL1, M.REMATCH, M.DATES
FROM MATCHES M
INNER JOIN TEAM_NAMES N1 ON N1.TEAMFK = M.TEAM1FK
INNER JOIN TN1 ON TN1.TEAMFK = N1.TEAMFK AND TN1.DATEFROM = N1.DATEFROM
INNER JOIN TEAM_NAMES N2 ON N2.TEAMFK = M.TEAM2FK
INNER JOIN TN1 TN2 ON TN2.TEAMFK = N2.TEAMFK AND TN2.DATEFROM = N2.DATEFROM
WHERE M.ROUNDFK = 10568 AND M.GROUPNR = 1
--- Konec kódu ---
Ako sa to dá vyriešiť?
Stanislav Hruška:
Samozrejme, že mi prišlo na um ešte jedno funkčné riešenie.
Podmienku pre rok som dal samostatne pre N1 a N2. Samozrejme, že WITH som vyhodil.
Ďakujem.
Jan Fiala:
Na prirazeni jmen bych pouzil outer join, ne inner join
Tu podminku na datum muzes dat rovnou do podminky za join
Pak z toho mas jednoduchy dotaz
--- Kód: ---SELECT N1.ACRONYM AS TITLE2, N2.ACRONYM, M.GOAL2, M.GOAL1, M.REMATCH, M.DATES
FROM MATCHES M
LEFT OUTER JOIN TEAM_NAMES N1 ON N1.TEAMFK = M.TEAM1FK AND EXTRACT(YEAR FROM N1.DATEFROM) <= 2006 AND ((EXTRACT(YEAR FROM N1.DATETO) >= 2006) OR
(N1.DATETO IS NULL))
LEFT OUTER JOIN TEAM_NAMES N2 ON N2.TEAMFK = M.TEAM2FK AND EXTRACT(YEAR FROM N2.DATEFROM) <= 2006 AND ((EXTRACT(YEAR FROM N2.DATETO) >= 2006) OR
(N2.DATETO IS NULL))
WHERE M.ROUNDFK = 10568 AND M.GROUPNR = 1
--- Konec kódu ---
Stanislav Hruška:
Ďakujem. Preštudujem si to. Aby som to pochopil a v prípade vhodnej situácie to použil.
Svoje riešenie už nebudem prerábať.
Navigace
[0] Seznam témat
Přejít na plnou verzi