2012-01-12 57 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