douzhi2760 2015-09-15 16:05
浏览 41
已采纳

SQL如何在一条记录中获取OR语句

I have a query that returns more than one record because I am using an or

    SELECT m_o.ordernum, m_CD.fieldvalue
    FROM measurements.orders m_o
    INNER JOIN measurements.custom_data m_cd
    ON m_cd.ordernum = m_o.ordernum
    WHERE m_o.custnum = 'xxx'
    AND (m_cd.fieldname = 'primary_name' or m_cd.fieldname = 'secondary_name');

There is a way to get this returning one row but I am stumped.

  • 写回答

2条回答 默认 最新

  • dqpkea9486 2015-09-15 16:30
    关注

    To obtain the value associated with the primary name, if any, and the value associated with the secondary name, if any, in the same result rows, you can join measurements.custom_data twice. If you cannot rely on which one of those names has a value associated with it, then you must use outer joins. For example:

    SELECT
      m_o.ordernum,
      m_cd1.fieldvalue AS fieldValue1
      m_cd2.fieldvalue AS fieldValue2
    FROM
      measurements.orders m_o
      LEFT JOIN measurements.custom_data m_cd1
        ON m_cd1.ordernum = m_o.ordernum AND m_cd1.fieldname = 'primary_name'
      LEFT JOIN measurements.custom_data m_cd2
        ON m_cd2.ordernum = m_o.ordernum AND m_cd2.fieldname = 'secondary_name'
    WHERE
      m_o.custnum = 'xxx'
      AND (m_cd1.ordernum IS NOT NULL OR m_cd2.ordernum IS NOT NULL)
    

    Note that the fieldname predicates are moved into the (outer) join conditions. That directs which field value goes into which result column, and helps prevent duplicates.

    Note also the NOT NULL conditions in the WHERE clause. These prevent results being returned that have no value for either name.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于作物生长模型下,有限水资源的最大化粮食产量的资源优化模型建立
  • ¥20 关于变压器的具体案例分析
  • ¥15 生成的QRCode圖片加上下載按鈕
  • ¥15 板材切割优化算法,数学建模,python,lingo
  • ¥15 科来模拟ARP欺骗困惑求解
  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式