将自联接表加入另一个表

时间:2017-07-28 12:36:45

标签: mysql

我有两个表:产品和元。

产品表:

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

元表:

+----+------------+-----------+------------+
| 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       |
+----+------------+-----------+------------+

现在以下查询正常工作:

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';

结果:

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

但查询:

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';

返回:"未知列' price.product_id'在' on''"

为什么会这样?

1 个答案:

答案 0 :(得分:2)

您的“from”子句被解释为:

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

因此,on子句没有price.product_id可用,因为它只知道meta as currencyproducts表。