2011-08-09 51 views
0

我有一個mysql語句,用於匹配字符串到兩個數據庫中的字符串。我想排除也在另一個表中的結果,但是當我添加conv_progress的左連接時,它會打破語句。任何人有任何想法如何排除在另一個表中的條目?搜索左加入null

作品

SELECT video.*, 
    MATCH(video.title) AGAINST(? IN BOOLEAN MODE) as cscore, 
    MATCH(tags.name) AGAINST(? IN BOOLEAN MODE) as htscore 
FROM video 
LEFT JOIN tags ON video.vid_id=tags.vid_id 
null 
WHERE 
    MATCH(video.title) AGAINST(? IN BOOLEAN MODE) OR 
    MATCH(tags.name) AGAINST(? IN BOOLEAN MODE) GROUP BY video.vid_id 
ORDER BY cscore DESC LIMIT ?, ? 

破碎

SELECT video.*, 
    MATCH(video.title) AGAINST(? IN BOOLEAN MODE) as cscore, 
    MATCH(tags.name) AGAINST(? IN BOOLEAN MODE) as htscore 
FROM video 
LEFT JOIN tags ON video.vid_id=tags.vid_id 
LEFT JOIN conv_progress on video.vid_id=conv_progress.vid_id where conv_progress.vid_id is null 
WHERE 
    MATCH(video.title) AGAINST(? IN BOOLEAN MODE) OR 
    MATCH(tags.name) AGAINST(? IN BOOLEAN MODE) GROUP BY video.vid_id 
ORDER BY cscore DESC LIMIT ?, ? 

回答

1

移動conv_progress.vid_id is null到WHERE子句:

SELECT video.*, 
    MATCH(video.title) AGAINST(? IN BOOLEAN MODE) as cscore, 
    MATCH(tags.name) AGAINST(? IN BOOLEAN MODE) as htscore 
FROM video 
LEFT JOIN tags ON video.vid_id=tags.vid_id 
LEFT JOIN conv_progress on video.vid_id=conv_progress.vid_id 
WHERE 
    (
    MATCH(video.title) AGAINST(? IN BOOLEAN MODE) OR 
    MATCH(tags.name) AGAINST(? IN BOOLEAN MODE) 
) 
    AND conv_progress.vid_id is null 
GROUP BY video.vid_id 
ORDER BY cscore DESC LIMIT ?, ? 
+0

感謝你的朋友你是我的英雄。 – Scarface

1

您還可以使用NOT EXISTS而不是加入

SELECT video.*, 
    MATCH(video.title) AGAINST(? IN BOOLEAN MODE) as cscore, 
    MATCH(tags.name) AGAINST(? IN BOOLEAN MODE) as htscore 
FROM video 
LEFT JOIN tags ON video.vid_id=tags.vid_id 
null 
WHERE 
    (
    MATCH(video.title) AGAINST(? IN BOOLEAN MODE) OR 
    MATCH(tags.name) AGAINST(? IN BOOLEAN MODE) 
)AND(NOT EXISTS(SELECT 1 FROM conv_progress WHERE video.vid_id=conv_progress.vid_id)) 
GROUP BY video.vid_id 
ORDER BY cscore DESC LIMIT ?, ? 
+0

感謝哥們。嵌套查詢不會稍微慢一些嗎? – Scarface

+0

我想這取決於。有時候'存在'可以得到很好的優化......你必須測試一下,看看哪一個數據更快。 – ain

+0

您可以在SELECT部分​​之前使用EXPLAIN來查看數據庫如何搜索其結果。我認爲tags.vid_id列上的索引是一個很好的性能提升。 – Bearwulf