mysql - 将此INNER JOIN转换为UNION

时间:2013-09-12 14:42:20

标签: mysql sql

我无法让这个工作。我想将此查询转换为UNION以删除notifies的INNER JOIN中的OR。

SELECT posts.status, posts.reports, posts.private_id,
    enter code hereposts.parent_id, posts.post_id,
    posts.reply_counts, posts.sender, posts.content, 
    posts.image, posts.thumb, posts.date,members.username, 
    members.avatar,members.avatar_path,members.level, members.state 
FROM posts
INNER JOIN members ON posts.sender = members.member_id 
INNER JOIN notifies ON (
    posts.post_id=notifies.post_id OR posts.parent_id=notifies.post_id
) 
WHERE  (posts.date>notifies.last_date AND posts.sender<>1) 
    AND notifies.member_id=1 
    AND posts.private_id<>0 
    AND posts.status=1 
    AND posts.reports<3  
ORDER BY posts.last_update DESC, posts.date DESC LIMIT 0,25;

我的尝试不起作用:

(SELECT posts.status, posts.reports, posts.private_id , posts.parent_id, 
    posts.post_id, posts.reply_counts, posts.sender, posts.content, 
    posts.image, posts.thumb, posts.date, members.username, members.avatar,
    members.avatar_path,members.level, members.state 
FROM posts 
INNER JOIN members ON posts.sender = members.member_id 
INNER JOIN notifies ON posts.parent_id=notifies.post_id) 

UNION

(SELECT posts.status, posts.reports, posts.private_id , posts.parent_id,  
    posts.post_id, posts.reply_counts, posts.sender, posts.content, 
    posts.image, posts.thumb, posts.date, members.username, members.avatar,
    members.avatar_path,members.level, members.state 
FROM posts 
INNER JOIN members ON posts.sender = members.member_id 
INNER JOIN notifies ON posts.post_id=notifies.post_id) 
WHERE  (posts.date>notifies.last_date AND posts.sender<>1) 
    AND notifies.member_id=1 
    AND posts.private_id<>0
    AND posts.status=1 
    AND posts.reports<3  
ORDER BY posts.last_update DESC, posts.date DESC LIMIT 0,25;

2 个答案:

答案 0 :(得分:3)

您似乎只将where子句添加到UNION的最后一部分,而不是两者都添加。

所以你从

开始
SELECT *
FROM  A INNER JOIN
B ON (a.ID = b.ID OR a.ID = b.ID2)
WHERE tada

SELECT *
FROM  A INNER JOIN
B ON (a.ID = b.ID)
UNION
SELECT *
FROM  A INNER JOIN
B ON (a.ID = b.ID2)
WHERE tada

所以你需要做一些像

这样的事情
SELECT *
FROM  A INNER JOIN
B ON (a.ID = b.ID)
WHERE tada
UNION
SELECT *
FROM  A INNER JOIN
B ON (a.ID = b.ID2)
WHERE tada

答案 1 :(得分:1)

您无需将其更改为union以提高效率。以下是替代版本(仅显示fromwhere子句):

FROM   posts 
       INNER JOIN members 
               ON posts.sender = members.member_id 
       LEFT JOIN notifies n 
               ON ( posts.post_id = n.post_id ) 
       LEFT JOIN notifies np 
               ON ( posts.parent_id = np.post_id ) 
WHERE  ( (posts.date > n.last_date or posts.date > np.last_date)) AND posts.sender <> 1 ) 
       AND (n.member_id = 1 or np.member_id = 1)
       AND posts.private_id <> 0 
       AND posts.status = 1 
       AND posts.reports < 3 

当父级和帖子匹配时,这也会删除重复的行。

我并不认为日期比较正是你想要的,但它应该是接近的。