I have two tables like that:
summary(id, status, value, time, aperson) and long_summary(id, who, comment, alltext)
for that i have tried with below query like:
SELECT l.id,summary.status
FROM long_summary l INNER JOIN summary ON l.id = summary.id INNER JOIN long_summary ON summary.aperson = long_summary.who
WHERE summary.status IN('old','new','waiting')
AND summary.value IN ('')
AND summary.time >= DATE_SUB(NOW(),INTERVAL 2 MONTH)
AND l.alltext LIKE '% relational database management system %' ORDER BY FIELD(summary.status,'old','new','waiting'),summary.time DESC
While running it is giving correct output but retured rows are comming multiple times like:
(1,'old')
(1,'old')
(1,'old')
(2,'new')
(2,'new')
(3,'new')
(4,'waiting')
(4,'waiting')
For that i have used SELECT DISTINCT and after that it is giving correct output without repetition of the single row. But i am not getting what i have done wrong?
Will you please suggest?
The way to see what’s happening is to (a) create a stripped-down test case, and (b) do a
SELECT *so you can see what you’re getting back in the other columns, that’s causing the repetition.So, I did this:
Then I took a simpler version of your query:
None of the other stuff could make things any worse, right? So it’s irrelevant. What do I get when I run this? 9 copies of
1|old, and 12 copies of2|new.So, let’s change it to see the whole row:
OK, now you can see the problem, let’s see why it’s happening. Is each of these rows supposed to be there? In other words, should you see a
1|oldif at least one of the first three combinations are there?If not, which ones shouldn’t be causing it? You need to filter something out in either the
WHEREor theJOIN.If so, then you need a
GROUP BYto merge together the relevant fields, or anORsomewhere, more likely the first.Step through all of the groups asking the same question. If you get to the point where you need a
GROUP BYon the columns you’re actually displaying, it’s simpler to just use aSELECT DISTINCT.You also might want to step back and ask whether you really want a full
JOINof long_summary with summary with long_summary. That’s 8*3*8=192 rows that you’ve filtered down to 21. Does that make sense, or did you only expect, say, 24 rows to filter down? If the latter, you’ve got theJOINwrong. Either one of thoseJOINs shouldn’t be there at all, or it should be a one-to-one instead of one-to-manyJOIN, or something else is wrong with it.By the way, you might be able to tell from my test above that I used
sqlite3rather thanmysql, just because it’s a lot simpler to get and running. I doubt that makes any difference, but if you test inmysqland see different results, by all means let me know.