我有一个返回多条记录的查询,因为我使用的是
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');
有一种方法可以让这一行返回,但我很难过。
答案 0 :(得分:1)
您可以使用case
然后在ordernum上进行汇总,因为您的字段名最多只有2个值。
SELECT m_o.ordernum,
max(case when m_cd.fieldname = 'primary_name' then m_CD.fieldvalue end) as col1,
max(case when m_cd.fieldname = 'secondary_name' then m_CD.fieldvalue end) as col2
FROM measurements.orders m_o
INNER JOIN measurements.custom_data m_cd
ON m_cd.ordernum = m_o.ordernum
WHERE m_o.custnum = 'xxx'
group by m_o.ordernum
答案 1 :(得分:0)
要获取与主要名称(如果有)相关联的值以及与同一结果行中的辅助名称(如果有)关联的值,您可以加入measurements.custom_data
两次。如果您不能依赖这些名称中的哪一个具有与之关联的值,则必须使用外部联接。例如:
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)
请注意,fieldname
谓词将移入(外部)连接条件。这指示哪个字段值进入哪个结果列,并有助于防止重复。
还请注意NOT NULL
子句中的WHERE
条件。这些会阻止返回的结果 名称无效。