2012-01-25 42 views
0

因此,我遇到了以下查询的问题。所以,查询只选择了comment.author_id或者stream.author_id进行插入,而我需要它来选择符合where条件的地方,所以它为流项作者ID和与目标流ID相关联的所有评论的作者ID插入通知。所有帮助表示赞赏MySQL COALESCE替代选择插入的两个结果集,而不是/或?

INSERT INTO notification 
     (text, type, target_id, sender_id, recipient_id, data, timestamp, is_unread) 
SELECT DISTINCT '$text', 'comment', '$id', '$senderId', 
     COALESCE(comment.author_id, stream.author_id), 
     '$dataArray','$timestamp', '1' 
FROM stream 
    LEFT JOIN comment ON comment.target_id = stream.id 
WHERE (comment.target_id = '$id' OR stream.id = '$id') 
    AND comment.author_id != '$senderId'" 
    AND stream.author_id != '$senderId' 
+3

你不应该插入到一个字段。如果你需要两个,有2个独立的列 – gbn

回答

0

我同意gbn。如果由于某种原因你必须连接它们,你可以使用concat()或concat_ws()函数。

CONCAT(COL1,COL2,...):

select concat('a','b','c'); 

返回:

ABC

CONCAT_WS(分体,COL1,COL2,...):

select concat_ws(',','a','b','c'); 

退货:

A,B,C

您需要注意与铸造类型的特殊情况。请参阅本手册中的String Functions