【问题标题】:Query with data that it may not be exist查询可能不存在的数据
【发布时间】:2013-01-27 15:52:07
【问题描述】:

我有两张桌子

Customer

  • cus_id
  • cus_name

表购买

  • buy_id,
  • cus_id(FK 到客户),
  • 价格

我想要的结果

cus_id, cus_name, buy_id, price

但万一有些客户没有buy_id。我怎么能这样查询。

cus_id, cus_name, null, null

【问题讨论】:

    标签: mysql sql select join


    【解决方案1】:

    如果您想显示所有客户,即使他还没有购买任何东西,请使用LEFT JOIN

    SELECT  a.*, b.buy_id, b.price
    FROM    customer a
            LEFT JOIN buying b
                ON a.cus_id = b.cus_id
    

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

    【讨论】:

    • 谢谢。我也想知道如何在帖子中制作灰色背景。
    • 选择你想要的代码,然后在编辑器工具上点击{ }
    • 可以将空词改为不同的词。
    • @aratn0n 是的,使用COALESCE,例如COALESCE(columnName, 'xx'),如果该列的值为空,它将显示xxMySQL COALESCE (click here)
    【解决方案2】:

    通过使用LEFT JOIN:

    Select 
    c.cus_id, 
    cus_name, 
    buy_id, 
    price
    from 
    Customers c
    LEFT JOIN Buying b on (c.cus_id=b.cus_id)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-22
      • 1970-01-01
      • 2012-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多