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

Un modo migliore per cercare i tag in una tabella MySQL

Quando l'elemento A può essere associato a molti elementi B, e l'elemento B può essere associato a molti elementi A. Questa si chiama relazione molti-a-molti.

I dati con questa relazione vanno memorizzati in una tabella separata e uniti solo in fase di query.

Esempio.

Tabella 1

| product_uid | price | amount | | 1 | 12000 | 3000 | | 2 | 30000 | 600 | 

Tabella 2

| tag_uid | tag_value | | 1 | tag_01 | | 2 | tag_02 | | 3 | tag_03 | | 4 | tag_04 | 

Poi usiamo una tabella di join per collegarle.

Tabella 3

| entry_uid | product_uid | tag_uid | | 1 | 1 | 3 | | 2 | 1 | 4 | | 3 | 2 | 1 | | 4 | 2 | 2 | | 5 | 4 | 2 | 

La query sarà (se vuoi selezionare l'elemento uno e il tag):

SELECT t1.*, t2.tag_value FROM Table1 as t1, JOIN Table3 as join_table ON t1.product_uid = join_table.product_uid JOIN Table2 as t2 ON t2.tag_uid = join_table.tag_uid WHERE t1.product_uid = 1