【问题标题】:Merging columns in INNER/LEFT JOIN returns NULL values?合并 INNER/LEFT JOIN 中的列返回 NULL 值?
【发布时间】:2015-01-13 03:49:45
【问题描述】:

我遇到了一个问题,我连接了多个表,但我需要合并 e.urlf.url_new 列。否则,结果如预期。这是我的查询。

SELECT a.`added_date`,b.`type`,c.`action`,e.`url`,f.`url_new` 
FROM `websites_submitted_main` a
INNER JOIN `websites_submitted_type` b ON a.`type_id` = b.`type_id` 
INNER JOIN `websites_submitted_action` c ON a.`action_id` = c.`action_id`
INNER JOIN `users` d ON a.`user_id` = d.`user_id`
LEFT JOIN `websites` e ON a.`url_id` = e.`id`
LEFT JOIN `websites_submitted_new` f ON a.`url_new_id` = f.`url_new_id`
WHERE a.`user_id` = 1 ORDER BY a.`added_date` DESC

我尝试过CONCAT,但该列包含所有NULL 值。这是那个查询。

SELECT a.`added_date`,b.`type`,c.`action`,CONCAT(e.`url`,f.`url_new`) AS url 
FROM `websites_submitted_main` a
INNER JOIN `websites_submitted_type` b ON a.`type_id` = b.`type_id` 
INNER JOIN `websites_submitted_action` c ON a.`action_id` = c.`action_id`
INNER JOIN `users` d ON a.`user_id` = d.`user_id`
LEFT JOIN `websites` e ON a.`url_id` = e.`id`
LEFT JOIN `websites_submitted_new` f ON a.`url_new_id` = f.`url_new_id`
WHERE a.`user_id` = 1 ORDER BY a.`added_date` DESC

我可以对此查询进行细微修改以合并这些列吗?

【问题讨论】:

  • 我会说 CONCAT 应该可以工作,但你试过 e.url || f.url_new 吗?
  • 仍然在url 列中返回NULL 值:(

标签: mysql left-join concatenation inner-join


【解决方案1】:

尝试使用CONCAT_WS() 而不是CONCAT()

SELECT  `CONCAT_WS(' ',e.url, f.url_new )` ....

CONCAT_WS() 将在值不为空时连接这些值。

来自CONCAT()的手册

如果任何参数为 NULL,CONCAT() 将返回 NULL。

SELECT a.`added_date`,b.`type`,c.`action`,CONCAT_WS("", e.`url`,f.`url_new`) AS url 
FROM `websites_submitted_main` a
INNER JOIN `websites_submitted_type` b ON a.`type_id` = b.`type_id` 
INNER JOIN `websites_submitted_action` c ON a.`action_id` = c.`action_id`
INNER JOIN `users` d ON a.`user_id` = d.`user_id`
LEFT JOIN `websites` e ON a.`url_id` = e.`id`
LEFT JOIN `websites_submitted_new` f ON a.`url_new_id` = f.`url_new_id`
WHERE a.`user_id` = 1 ORDER BY a.`added_date` DESC

【讨论】:

  • 如果任何参数为空,CONCAT() 将返回空。 CONCAT_WS() 忽略空值并继续下一个参数
猜你喜欢
  • 2017-04-06
  • 1970-01-01
  • 1970-01-01
  • 2014-11-15
  • 1970-01-01
  • 2012-08-10
  • 1970-01-01
  • 2017-12-07
  • 2013-05-13
相关资源
最近更新 更多