Mysql
 SQL >> Database >  >> RDS >> Mysql

Come memorizzare i tag in un database con MySQL e PHP

La soluzione corretta è separare i dati in due tabelle, questions e tags, collegate da una tabella di giunzione questions_tags.

CREATE TABLE questions (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  url TEXT NOT NULL,
  PRIMARY KEY (id)
);

CREATE TABLE tags (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  tag VARCHAR(255) NOT NULL,
  PRIMARY KEY (id)
);

CREATE TABLE questions_tags (
  question_id INT UNSIGNED NOT NULL REFERENCES questions,
  tag_id INT UNSIGNED NOT NULL REFERENCES tags
);

Non ho incluso la colonna count della tua tabella originale perché non era chiaro a cosa servisse.

Con questo schema puoi usare le JOIN per trovare tutte le domande con un certo tag o tutti i tag di una domanda.

Contare i tag

SELECT tag, COUNT(*) AS c FROM tags GROUP BY tag;

Conteggio per domanda

SELECT t.tag, q.id AS question_id, COUNT(*) AS c
FROM tags AS t
JOIN questions_tags AS qt ON t.id = qt.tag_id
JOIN questions AS q ON qt.question_id = q.id
GROUP BY t.id, q.id;

Per limitare il conteggio a tag o domande specifici, aggiungi le opportune clausole WHERE.

Nota: valuta anche un indice su questions_tags(question_id, tag_id) e un vincolo di unicità sulla coppia, per evitare duplicati.