【问题标题】:MySQL Complex Insert With Conditional Subselect?带有条件子选择的 MySQL 复杂插入?
【发布时间】:2012-01-12 02:44:51
【问题描述】:

所以我无法正确创建此查询。

基本上,我想在通知表中插入多行,插入的每一行都有一个不会重复的唯一收件人 ID,收件人 ID 是通过检查评论的匹配 target_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'

【问题讨论】:

    标签: php mysql insert


    【解决方案1】:

    你所拥有的似乎很好。您可以尝试使用COALESCE(stream.author_id, comment.author_id),因此如果评论 author_id 为空(例如,因为 author_id 是发件人),它将退回到流的 author_id。为此,您必须在流上外部加入评论,并且stream.author_id != '$senderId' 条件必须是ON 子句的一部分。

    【讨论】:

    • 那么查询的结构如何?我没有使用 Coalesce 的经验
    • 只是COALESCE(field1, field2)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多