Recupero di una riga, con i dati di valore-chiave tabella pair in MySQL
Domanda
Ho due tabelle, una chiamata customer
e uno chiamato customer_attributes
.
L'idea è che la tabella di clienti contiene dati dei clienti di base, e l'applicazione può essere personalizzata per supportare gli attributi aggiuntivi a seconda di come viene utilizzato.
customer_attributes
ha le seguenti 3 colonne:
customerID
key1
value1
Posso recuperare la riga pieno, con eventuali attributi aggiuntivi se specificato, il valore predefinito è NULL, se no? Sto utilizzando la seguente query ma funziona solo se esistono entrambi gli attributi nella tabella customer_attributes.
SELECT `customer`.*, `ca1`.`value1` AS `wedding_date`, `ca2`.`value1` AS `test`
FROM `customer`
LEFT JOIN `customer_attributes` AS `ca1` ON customer.customerID = ca1.customerID
LEFT JOIN `customer_attributes` AS `ca2` ON customer.customerID = ca2.customerID
WHERE (customer.customerID = '58029')
AND (ca1.key1 = 'wedding_date')
AND (ca2.key1 = 'test')
In questo caso i due attributi che mi interessano sono chiamati 'wedding_date' e 'test'
Soluzione
Prova questo:
SELECT `customer`.*, `ca1`.`value1` AS `wedding_date`, `ca2`.`value1` AS `test`
FROM `customer`
LEFT JOIN `customer_attributes` AS `ca1` ON customer.customerID = ca1.customerID AND ca1.key1='wedding_date'
LEFT JOIN `customer_attributes` AS `ca2` ON customer.customerID = ca2.customerID AND ca2.key1='test'
WHERE (customer.customerID = '58029')
Lo spostamento del 2 WHERE condizioni CA1 / Ca2 nella condizione di join invece dovrebbe risolvere la
Altri suggerimenti
Il motivo righe vengono restituite solo è a causa dei test nella clausola WHERE. Eventuali righe che non hanno la corretta key1 vengono ignorati del tutto -. Negando la tua LEFT JOIN
Si potrebbe spostare i test key1 alle condizioni ABBONATI A
SELECT `customer`.*, `ca1`.`value1` AS `wedding_date`, `ca2`.`value1` AS `test`
FROM `customer`
LEFT JOIN `customer_attributes` AS `ca1` ON customer.customerID = ca1.customerID AND ca1.key1 = 'wedding_date'
LEFT JOIN `customer_attributes` AS `ca2` ON customer.customerID = ca2.customerID AND ca2.key1 = 'test'
WHERE (customer.customerID = '58029')
Le prove di "chiave" in con il LEFT OUTER JOIN predicati, come ad esempio:
SELECT `customer`.*, `ca1`.`value1` AS `wedding_date`, `ca2`.`value1` AS `test`
FROM `customer`
LEFT JOIN `customer_attributes` AS `ca1` ON customer.customerID = ca1.customerID
AND (ca1.key1 = 'wedding_date')
LEFT JOIN `customer_attributes` AS `ca2` ON customer.customerID = ca2.customerID
AND (ca2.key1 = 'test')
WHERE (customer.customerID = '58029')