MySQL复杂插入带条件子选择


MySQL Complex Insert With Conditional Subselect?

所以我在正确创建这个查询时遇到了问题。

基本上,我想在通知表中插入多行,插入的每一行都有一个不会重复的唯一收件人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'

您所拥有的似乎很好。您可以尝试使用COALESCE(stream.author_id, comment.author_id),这样,如果注释author_id为null(例如,因为author_id是发送方),它将返回流的author_id。为了实现这一点,您必须在流上外部联接注释,并且stream.author_id != '$senderId'条件必须是ON子句的一部分。