Question

Salut j'ai tables comme ceci:

entrée de la table:

id | total_comments
_____________________
1 | 0
2 | 0
3 | 0
4 | 0

Commentaires de table:

id | eid | commentaire
_____________________
1 | 1 | commentaires sdfd
2 | 1 | test test
3 | 1 | commentaire du texte
4 | 2 | mannequin commentaire
5 | 2 | échantillon
commentaire 6 | 1 | fg FGH DFH

Requête i écrire:

UPDATE entry 
   SET total_comments = total_comments + 1 
 WHERE id IN ( SELECT eid 
                 FROM comments 
                WHERE id IN (1,2,3,4,5,6))

Résultats que je reçois est:

entrée de la table:

id | total_comments
_____________________
1 | 1
2 | 1
3 | 0
4 | 0

Résultats attendus:

entrée de la table:

id | total_comments
_____________________
1 | 4
2 | 2
3 | 0
4 | 0

Toute aide sera appréciée.

Était-ce utile?

La solution

Utilisation:

UPDATE entry 
   SET total_comments = (SELECT COUNT(*)
                           FROM COMMENTS c
                          WHERE c.eid = id
                       GROUP BY c.eid)
 WHERE id IN ( SELECT eid 
                 FROM comments 
                WHERE id IN (1,2,3,4,5,6))

Autres conseils

Si vous avez vraiment besoin total_comments dans une table séparée, je en faire une VIEW.

CREATE VIEW entry AS 
  SELECT id, COUNT(comments) AS total_comment 
  FROM comments 
  GROUP BY id

De cette façon, vous éviter la tâche de maintenance de mettre à jour la table total_comments tout à fait.

C'est exactement ce que je pense. L'id est dans l'ensemble que vous donnez, donc total_comments = total_comments + 1.

Il ne va pas ajouter un pour chaque instance de la même valeur: ce n'est pas comment fonctionne IN. IN retournera un oui booléenne simple / non.

Essayez:

UPDATE entry
  SET total_comments = (SELECT COUNT(*) 
                        FROM comments
                        WHERE entry.id = comments.eid
                        GROUP BY id)
UPDATE entry e 
    SET total_comments = ( SELECT COUNT(*) FROM comments WHERE eid = e.id)  
    WHERE 
    e.id in (SELECT eid FROM comments WHERE id IN (1,2,3,4,5,6))
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top