【问题标题】:How to list two joined tables info by name (some with name, some possible empty)如何按名称列出两个连接表信息(有些带有名称,有些可能为空)
【发布时间】:2013-01-17 05:59:01
【问题描述】:

我有两张这样的桌子

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_id by customer_name asc 的发票。

【问题讨论】:

    标签: php mysql sql select


    【解决方案1】:

    请改用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
    

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

    【讨论】:

      【解决方案2】:
      SELECT  
          a.*, 
          b.customer_name
      FROM    Invoice a
      LEFT JOIN Customers b ON a.customer_ID = b.customerID
      

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

      【讨论】:

        【解决方案3】:

        使用这个

         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
        

        【讨论】:

        • 这是什么? ~Invoice.customer_id 我试图运行该语句,但它会生成未知的随机数。无论如何,OP 对数据的排序不感兴趣。
        猜你喜欢
        • 2017-06-18
        • 2022-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多