2017-07-28 7 views
1

Ich habe zwei Tabellen: Produkte und Meta.Join Self-Join-Tabelle mit einer anderen Tabelle

Produkte Tabelle:

+----+----------+ 
| id | name  | 
+----+----------+ 
| 1 | TV  | 
| 2 | Computer | 
| 3 | Freezer | 
+----+----------+ 

Meta Tabelle:

+----+------------+-----------+------------+ 
| id | product_id | meta_key | meta_value | 
+----+------------+-----------+------------+ 
| 1 |   1 | currency | USD  | 
| 2 |   1 | price  | 1100  | 
| 3 |   2 | currency | PLN  | 
| 4 |   2 | price  | 9300  | 
| 5 |   3 | currency | USD  | 
| 6 |   3 | price  | 1200  | 
+----+------------+-----------+------------+ 

nun die folgende Abfrage funktioniert gut:

select price.product_id, products.name, price.meta_value as 'price', currency.meta_value as 'currency' 
from meta as price 
join meta as currency on(price.product_id=currency.product_id and currency.meta_key='currency') 
join products on(products.id=price.product_id) 
where price.meta_key='price'; 

Ergebnis:

+------------+----------+-------+----------+ 
| product_id | name  | price | currency | 
+------------+----------+-------+----------+ 
|   1 | TV  | 1100 | USD  | 
|   2 | Computer | 9300 | PLN  | 
|   3 | Freezer | 1200 | USD  | 
+------------+----------+-------+----------+ 

aber die Abfrage:

select price.product_id, products.name, price.meta_value as 'price', currency.meta_value as 'currency' 
from meta as price, meta as currency 
join products on(products.id=price.product_id) 
where 
    price.product_id=currency.product_id 
    and price.meta_key='price' 
    and currency.meta_key='currency'; 

kehrt: "Unknown column 'price.product_id' in 'on-Klausel'"

Warum ist das passiert ist?

from meta as price, (meta as currency join products on (products.id = price.product_id)

gibt es keine price.product_id zur Verfügung, die on-Klausel, da er nur weiß um die meta as currency und products Tabellen Also:

Antwort

2

Ihre „von“ Klausel als interpretiert.

+0

Das macht Sinn, ich habe versucht mit der "Währung" und jetzt funktioniert es. Vielen Dank – ArturoO

Verwandte Themen