1

我有两张这样的桌子

Invoice   (invoice_no, invoice_date, customer_id, ...),  
Customers (customer_id, customer_name, ...)

现在我要做的是列出按客户名称排序的发票。

SELECT b.customer_name, a.*
FROM Invoice a, Customers b
WHERE a.customer_id=b.customer_id
ORDER BY b.customer_name

但是这个 sql 的问题是,如果有发票没有customer_id,我怎么能先列出这些发票,然后customer_idcustomer_nameasc 列出发票。

4

3 回答 3

3

改为使用LEFT JOIN

“有点怪异。为什么有些发票没有客户?你发给谁?无论如何,这是查询。

SELECT  a.*, b.*  // SELECT only the columns you want
FROM    Invoice a
        LEFT JOIN Customers b
            ON a.customer_ID = b.customer_ID

要全面了解联接,请访问以下链接:

于 2013-01-17T06:00:39.707 回答
0
SELECT  
    a.*, 
    b.customer_name
FROM    Invoice a
LEFT JOIN Customers b ON a.customer_ID = b.customerID

使用连接而不是 FROM tablea、tableb。因为这将从两个表中获取笛卡尔积,除非您使用 WHERE 限制它们

于 2013-01-17T06:02:56.567 回答
0

用这个

 SELECT * FROM Invoice,customer where Invoice.customer_id=customer.customer_id ORDER BY IF(Invoice.customer_id is NULL , Invoice.customer_id, ~Invoice.customer_id) ASC
于 2013-01-17T06:04:47.033 回答