合并MySQL中的整个记录

时间:2014-01-24 11:08:08

标签: mysql coalesce

我目前正在MySQL查询中单独填充字段,但我想合并整个记录。

这可能吗?

SELECT la.id, 
COALESCE(( SELECT name FROM lookup_changed l0, 
           ( SELECT MAX(id) id 
             FROM lookup_changed     
             WHERE lookup_id = 26
           ) l1 
           WHERE l0.id = l1.id
         ), la.name) name,
COALESCE(( SELECT msisdn FROM lookup_changed l0, 
           ( SELECT MAX(id) id 
             FROM lookup_changed     
             WHERE lookup_id = 26
           ) l1 
           WHERE l0.id = l1.id
         ), la.msisdn) msisdn
FROM lookup_added la
WHERE la.id = 26

@Alma Do - 伪SQL是:

SELECT la.id, 
MULTICOALESCE(( SELECT <name, msisdn> FROM lookup_changed l0, 
                ( SELECT MAX(id) id 
                  FROM lookup_changed     
                  WHERE lookup_id = 26
                ) l1 
                WHERE l0.id = l1.id
              ), <la.name, la.msisdn>) <name, msisdn>
FROM lookup_added la
WHERE la.id = 26

1 个答案:

答案 0 :(得分:0)

由于COALESCE()“返回[s]第一个非NULL参数”,听起来你想要从查询集中检索“第一个非NULL结果”:

-- syntax error
SELECT COALESCE(
    SELECT a FROM ta,
    SELECT b FROM tb
);

-- roughly equates to
( SELECT a AS val FROM ta WHERE a IS NOT NULL ORDER BY a LIMIT 1 )
UNION
( SELECT b AS val FROM tb WHERE b IS NOT NULL ORDER BY b LIMIT 1 )
ORDER BY val LIMIT 1 ;

评论:

  • 我添加了ORDER BY条款,否则“第一行”意味着什么
  • 内部LIMIT 1子句是可选的(但允许及早修剪子结果)
  • 子查询周围的括号是必需的