查询给出重复结果?

时间:2011-10-08 10:38:47

标签: php mysql sql

这是我的疑问:

SELECT b.id,b.body FROM btin b
INNER JOIN nwork n ON (n.mem_id = b.mem_id)  
WHERE b.parentid = '0'
AND ('401' IN (n.frd_id, b.mem_id))
ORDER BY b.date DESC 
LIMIT 20 OFFSET 0

问题是它打印重复的结果。 我该如何优化这个

请帮忙 感谢

4 个答案:

答案 0 :(得分:1)

解决这个问题的三种方法(基本上你在nwork中有超过1行):

SELECT distinct b.id,b.body FROM btin b
INNER JOIN nwork n ON (n.mem_id = b.mem_id)  
WHERE b.parentid = '0'
AND ('401' IN (n.frd_id, b.mem_id))
ORDER BY b.date DESC 
LIMIT 20 OFFSET 0


SELECT  b.id,b.body 
FROM btin b
Where b.id in (SELECT  b.id FROM btin b  INNER JOIN nwork n ON (n.mem_id = b.mem_id)  
                WHERE b.parentid = '0' AND ('401' IN (n.frd_id, b.mem_id)))
ORDER BY b.date DESC 
LIMIT 20 OFFSET 0

SELECT  b.id,b.body FROM btin b
INNER JOIN nwork n ON (n.mem_id = b.mem_id)  
WHERE b.parentid = '0'
AND ('401' IN (n.frd_id, b.mem_id))
Group by b.id, b.body, b.date
ORDER BY b.date DESC 
LIMIT 20 OFFSET 0

答案 1 :(得分:0)

如果您尝试:

SELECT DISTINCT b.id,b.body FROM btin b
....

会发生什么?

答案 2 :(得分:0)

尝试使用

SELECT DISTINCT .......

OR

SELECT b.id,b.body FROM btin b
INNER JOIN nwork n ON (n.mem_id = b.mem_id)  
WHERE b.parentid = '0'
AND ('401' IN (n.frd_id, b.mem_id)) 
GROUP BY b.id
ORDER BY b.date DESC 
LIMIT 20 OFFSET 0

答案 3 :(得分:0)

改为使用group:

SELECT b.id,b.body FROM btin b
INNER JOIN nwork n ON (n.mem_id = b.mem_id)  
WHERE b.parentid = '0'
AND ('401' IN (n.frd_id, b.mem_id))
GROUP BY b.id
ORDER BY b.date DESC 
LIMIT 20 OFFSET 0