内部联接不输出id列

时间:2015-08-31 03:37:03

标签: sql join

我有一个不同表连接的查询

SELECT 
    cust_name, order_no, order_status, pay_method, pro_name, cust_city 
FROM 
    customers
INNER JOIN 
    orders ON customers.cust_id = orders.cust_id
INNER JOIN 
    pro_orders ON pro_orders.order_id = orders.order_id
INNER JOIN 
    products ON products.pro_id = pro_orders.pro_id 
ORDER BY 
    customers.cust_name ASC

我正在尝试从订单表&中输出order_id来自customer表的customer_id任何与其他表相关的id列都不会输出

2 个答案:

答案 0 :(得分:4)

尝试以下内容

    SELECT c.cust_id, c.cust_name,order_no,order_status,pay_method,pro_name,cust_city 
    FROM customers c
    INNER JOIN orders o ON c.cust_id = o.cust_id
    INNER JOIN pro_orders po ON po.order_id = o.order_id
    INNER JOIN products pr ON po.pro_id = pr.pro_id 
    ORDER BY c.cust_name ASC

这是因为cust_id列同时位于客户和订单表中。所以SQL不知道应该打印哪个表的cust_id。

此外,创建别名并在查询中使用这些别名也是最佳做法之一。它使查询更具可读性,并且不易出现上述错误。

答案 1 :(得分:1)

使用别名来避免含糊不清

SELECT 
    c.*, o.*, po.*, p.*
FROM 
    customers c
INNER JOIN 
    orders  o ON c.cust_id = o.cust_id
INNER JOIN 
    pro_orders po ON po.order_id = o.order_id
INNER JOIN 
    products p ON p.pro_id = po.pro_id 
ORDER BY 
    c.cust_name ASC