2012-01-12 52 views
1

所以我无法正确创建此查询。带有条件子选择的MySQL复杂插入?

基本上,我想在通知表中插入多行,插入的每行都有一个不会重复的唯一收件人ID,收件人ID是通过检查匹配的注释target_id或ID一个流并检查与每个评论/流相关联的author_id。此外,我希望查询排除与发件人ID匹配的author_id所选的行插入。

下面是一个粗略的基本上我需要的sql标记。

INSERT INTO 
notification (type, 
target_id, 
sender_id, 
recipient_id, 
data, 
timestamp, 
is_unread) 
SELECT DISTINCT 'comment', 
'$id', 
'$senderId', 
(comment.author_id OR stream.author_id), 
'$dataArray', 
'$timestamp', 
'1' 
FROM 
    stream, 
    comment 
WHERE 
    stream.author_id != '$senderId' 
    AND comment.author_id != '$senderId' 
    AND stream.id = '$id' 
    OR comment.target_id = '$id' 

回答

0

你看起来很好。您可以尝试使用COALESCE(stream.author_id, comment.author_id),因此如果comment_id为空(例如,因为author_id是发件人),它将回退到流的author_id。为此,您必须在流上添加外部注释,并且stream.author_id != '$senderId'条件必须是ON子句的一部分。

+0

查询的结构如何呢?我没有使用Coalesce的经验 – 2012-01-12 04:20:23

+0

它只是'COALESCE(field1,field2)' – 2012-01-12 04:29:14