1.3k Aufrufe
Gefragt in Datenbanken von
Hi Leute,
ich habe 2 tabelle, die eine heißt "topic", die andere "post".
der primary key in topic ist "id_topic" und der fremdschlüssel in post ebenfalls "id_topic".
so ist jedem post ein dazugehöriges topic zugeordnet.
jetzt möchte ich wissen, wieviele posts im topic mit der id_topic==2 sind.
ich hab schon echt viel ausprobiert,
select count(*) , id_topic
from post
group by id_topic

z.b gibt mir aus:
count(*) | id_topic
1 | 1
4 | 2

bedeutet also es gibt im topic 1 einen eintrag und in topic 2 4 einträge.,
jetzt will ich aber einfach nur eine 4 haben, damit ich diese sql-query, die mir die 4 liefert, gleich weiterverwenden kann, um "anzahl_posts" in topics zu updaten....
liebe grüße

3 Antworten

0 Punkte
Beantwortet von
select count(*)
from post
group by id_topic
having id_topic=2

bekomme ich jetzt nur die 4 ausgegeben. so solls sein. statt == nimmt man hier anscheinend nur ein =

aber wie schaff ich das jetzt mit den anzahl_post?
update topic
set anzahl_post=(select count(*)
from post
group by id_topic
having post.id_topic=topic.id_topic)
0 Punkte
Beantwortet von
ich hab mal noch ewig rumprobiert:
select count(*) from topic
group by topic.id_topic

gibt mir jetzt schön eine einspaltige tabelle aus, jede zeile steht für ein topic und die zahl dahinter sind die anzahll der posts.
bloß wie bekomm ich diese tabelle jetzt als spalte für "anzahl beiträge?!)
0 Punkte
Beantwortet von worm2012 Einsteiger_in (25 Punkte)
Hallo sql_newby

Probier's mal mit folgendem statement:

update topic t
set anzahl_posts = ( select count(*) from post p
where t.id_topic = p.id_topic)
where exists ( select 1 from post p
where t.id_topic = p.id_topic)


Gruss Rolf
...