Unire MySQL Python
- Pagina Precedente Limit MySQL
- Pagina Successiva Iniziare con MongoDB
Combinazione di due o più tabelle
Puoi usare la clausola JOIN per combinare le righe di due o più tabelle in base alle colonne correlate.
Supponiamo di avere le tabelle "users" e "products":
users
{ id: 1, name: 'John', fav: 154}, { id: 2, name: 'Peter', fav: 154}, { id: 3, name: 'Amy', fav: 155}, { id: 4, name: 'Hannah', fav:}, { id: 5, name: 'Michael', fav:}
products
{ id: 154, name: 'Chocolate Heaven' }, { id: 155, name: 'Tasty Lemons' }, { id: 156, name: 'Vanilla Dreams' }
Puoi usare il campo users fav
campo e products id
campo per combinare queste due tabelle.
Esempio
Combina gli utenti e i prodotti per vedere il nome del prodotto preferito dall'utente:
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", passwd="yourpassword", database="mydatabase" ) mycursor = mydb.cursor() sql = "SELEZIONARE \ users.name come utente, \ products.name come preferito \ DAL users \ UNIONE INTERNA products ON users.fav = products.id" mycursor.execute(sql) myresult = mycursor.fetchall() per x in myresult: print(x)
Nota:Puoi usare JOIN invece di UNIONE INTERNA. Otterrai lo stesso risultato.
UNIONE SINISTRA
In questo esempio, Hannah e Michael sono stati esclusi dai risultati perché l'UNIONE INTERNA mostra solo i record corrispondenti.
Se si desidera visualizzare tutti gli utenti, anche se non hanno prodotti preferiti, utilizzare la clausola UNIONE SINISTRA:
Esempio
Selezionare tutti gli utenti e i loro prodotti preferiti:
sql = "SELEZIONARE \ users.name come utente, \ products.name come preferito \ DAL users \ UNIONE SINISTRA products ON users.fav = products.id"
UNIONE DESTRA
Se si desidera restituire tutti i prodotti e gli utenti che li amano, anche se nessun utente li ama, utilizzare la clausola UNIONE DESTRA:
Esempio
Selezionare tutti i prodotti e gli utenti che li amano:
sql = "SELEZIONARE \ users.name come utente, \ products.name come preferito \ DAL users \ UNIONE DESTRA products ON users.fav = products.id"
Nota:Hannah e Michael, che non sono interessati a nessun prodotto, non sono inclusi nei risultati.
- Pagina Precedente Limit MySQL
- Pagina Successiva Iniziare con MongoDB