MYSQL UPDATE con IN e sottoquery
-
24-10-2019 - |
Domanda
Ciao ho tabelle in questo modo:
voce della tabella:
id | total_comments
_____________________
1 | 0
2 | 0
3 | 0
4 | 0
commenti di tabella:
id | eid | commento
_____________________
1 | 1 | commento sdfd
2 | 1 | Testing Testing
3 | 1 | testo di commento
4 | 2 | manichino commento
5 | 2 | campione commento
6 | 1 | fg fgh DFH
Query scrivo:
UPDATE entry
SET total_comments = total_comments + 1
WHERE id IN ( SELECT eid
FROM comments
WHERE id IN (1,2,3,4,5,6))
risultati che ottengo è:
voce della tabella:
id | total_comments
_____________________
1 | 1
2 | 1
3 | 0
4 | 0
Risultati attesi:
voce della tabella:
id | total_comments
_____________________
1 | 4
2 | 2
3 | 0
4 | 0
Ogni aiuto sarà apprezzato.
Soluzione
Usa:
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))
Altri suggerimenti
Se si ha realmente bisogno total_comments in una tabella separata, mi farebbe che una visione.
CREATE VIEW entry AS
SELECT id, COUNT(comments) AS total_comment
FROM comments
GROUP BY id
In questo modo si evita il compito di aggiornare la tabella total_comments del tutto la manutenzione.
Questo è esattamente ciò che mi aspettavo. L'ID è nel set si dà, in modo total_comments = total_comments + 1.
Non è intenzione di aggiungere uno per ogni istanza dello stesso valore: non è così che funziona IN. IN restituirà un semplice sì booleane / no.
Prova:
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))