2017-03-27 65 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); 
    });