webForumDet fria alternativet

Problem med left join.

4 svar · 496 visningar · startad av Jesper T

Jesper TMedlem sedan nov. 20017 058 inlägg
#1

Oavsätt om jag byter ut inner till Left eller right så visas inner join resultatet.
Jag skulle vilja ha alla poster ifrån tabellen "objecttype" oavsätt om personerna har poster vars "objecttype.id" motsvaras i tabellen "objecttype" eller ej.

SELECT ot.id, ot.typename, count(o.objectid) commonCount
FROM objectsusers o
inner JOIN objectsusers o2 ON o.objectid=o2.objectid
inner JOIN objects ob on o.objectid = ob.id
[blue][B]inner JOIN objecttype ot ON ot.id = ob.typeid[/B][/blue]
WHERE o.username = 'kalle' and o2.username = 'pelle'
group by ot.id
LarsGMedlem sedan dec. 200012 465 inlägg
#2
SELECT ot.id, ot.typename, count(o.objectid) commonCount
FROM  objecttype ot 
left JOIN objects ob ON ot.id = ob.typeid
left join objectsusers o on o.objectid = ob.id
and  o.username = 'kalle' 
left JOIN objectsusers o2 ON o.objectid=o2.objectid
and o2.username = 'pelle'
group by ot.id

Jag ändrade ordningen då jag tycker att det är enklare att se om du har huvudtabellen först, så det kan mycket väl ha blivit något fel där. I övrigt har jag bara flyttat lite villkor.

Jesper TMedlem sedan nov. 20017 058 inlägg
#3

Härligt, behövde bara ändra count(o.objectid) till count(o2.objectid).

Men när jag lägger till en subselect i satsen:

SELECT ot.id, ot.typename, count(o2.objectid) commonCount
,[blue](select count(*) FROM objectsusers ou 
 INNER JOIN objects ob2 on ou.objectid = ob2.id 
 WHERE ob2.typeid = ot.id and ou.username=o2.username) objCount[/blue]
FROM  objecttype ot 
...

Så visas märkligt nog endast resultatet på första raden.

1    Fåglar    4    14
2    Fiskar    15   [red]0[/red]
3    Bilar     0    0
...

Om jag testar den "enskilt" så ger den önskat resultat.

select count(*) FROM objectsusers ou 
 INNER JOIN objects ob2 on ou.objectid = ob2.id 
 WHERE ob2.typeid = 2 and ou.username='pelle';

Resultat: 27

MSDB=Mysql 5 (..som verkar göra lite som den vill.)

R/ OBS! Ändrat på kolumnerna i resultatet!

LarsGMedlem sedan dec. 200012 465 inlägg
#4

Ja, det är ju fel. Resultatet av en count kan aldrig bli null. Rapportera.

Jesper TMedlem sedan nov. 20017 058 inlägg
#5

Åhh, jag skrev null men menade 0 (redigerat). Men det är fortfarande inte rätt.

Genererad på 376 ms · cache AV · v20260730165559-full.f96bc7eb