2017-03-27 54 views
1

我想加入兩個表,計劃表和plan_details表。以下是表格的兩個例子。WHERE語句重複列名JOIN - PostgreSQL

圖則表

+---------+------+-----------+ 
| user_id | plan | is_active | 
+---------+------+-----------+ 
| 1  | 10 | true | 
| 1  | 11 | false | 
| 2  | 11 | true | 

PLAN_DETAILS表

+---------+------+-------+-----------+ 
| plan_id | cost | price | is_active | 
+---------+------+-------+-----------+ 
| 10  | 19 | 199 | true | 
| 11  | 13 | 149 | true | 

我只想只拉活動的計劃成本價格涉及到每個用戶。現在,我的knex說法是:

knex('plans') 
    .where({ 
    user_id: 1, 
    is_active: 'true' 
    }) 
    .select(
    'plans.plan', 
    'plan_details.cost', 
    'plan_details.price' 
) 
    .join('plan_details as plan_details', 'plan_details.plan_id', 'plans.plan') 
    .then(function (user_plan_id) { 
    console.log(user_plan_id); 
    }); 

現在,如果我繼續在那裏is_active: 'true'然後我得到一個Unhandled rejection error: column reference "is_active" is ambiguous。如果我取出is_active部分,那麼我可以獲得引用用戶的兩個計劃的信息,即使我只想知道關於哪些計劃對用戶有效的信息。

如何獲得用戶的活動計劃?我使用KNEX.JS作爲我的ORM,但我很樂意爲此使用原始SQL。

回答

0

SQL將類似於:

select 
    plans.plan, 
    plan_details.cost, 
    plan_details.price 
from plan 
join plan_details on plans.plan = plan_details.plan_id 
where plan.is_active 
1

隨着knex這應該這樣做:

knex('plans') 
    .select(
    'plans.plan', 
    'plan_details.cost', 
    'plan_details.price' 
) 
    .join('plan_details as plan_details', 'plan_details.plan_id', 'plans.plan') 
    .where('plan.user_id', 1) 
    .where('plan.is_active', true) 
    .then(function (user_plan_id) { 
    console.log(user_plan_id); 
    });