开发者

mySQL right outer join

Im quite new to SQL and am trying to construct a query:

$result = mysql_quer开发者_如何学编程y("SELECT COUNT(*) AS s_count FROM solution RIGHT OUTER JOIN 
ON offer.oid = solution.oid ". "WHERE offer.is_solved = 0  ORDER BY offer.creation_time 
DESC LIMIT $interval_begin, $interval_end");

The query is supposed to be a liveticker in a shop like environnment: it needs to count all offers that havent been solved and then list them for a certain interval to reflect a certain page of the listing. eg if there are 25 offers per age, page 2 would be 26-50.

Can anyone spot why the output is 0? All the columns/tables exist and do have test values in them.


Shouldn't the query be like

mysql_query("SELECT COUNT(*) AS s_count FROM solution RIGHT OUTER JOIN  offer ON offer.oid = solution.oid WHERE offer.is_solved = 0  ORDER BY offer.creation_time  DESC LIMIT".$interval_begin.",".$interval_end); 


looking into your question and your query, I think the most obvious reason(s) why your query always return 0 could be:

  1. The table offer does not have is_solved = 0 for any of its records. As a result, the WHERE condition offer.is_solved = 0 has no matching entries. Can you please confirm this for your data?

  2. The table offer has no data and thus the RIGHT JOIN yields no results. But as you have mentioned in one of your comments to Rahul's answer, there are 3000 entries in offer, I guess this reason is unlikely.

Aha, there could be another reason too: are you sure the limit and offset, marked by $interval_begin and $interval_end are correctly set? Perhaps if they are both set to 0, the query will always return 0. Can you try doing an "echo/print" of your query and see how does it exactly look?

Because I have no understanding of your schema, this is only a suggestion, I think that if you have an offer.is_solved column, you do not need a RIGHT JOIN with solution. The following query should work equally fine, no?

SELECT COUNT(*) AS `s_count`
FROM `offer`
WHERE `offer`.`is_solved` = 0
ORDER BY `offer`.`creation_time`
DESC LIMIT $interval_begin, $interval_end;

Hope it helps!


What for do you need solution table in your query? From your text it looks like

mysql_query("SELECT COUNT(*) FROM offer offer WHERE offer.is_solved = 0  ORDER BY offer.creation_time  DESC LIMIT".$interval_begin.",".$interval_end);

would be enough.

"What we need to know is the exact number of solutions for each "offer", not just whether there is any solution at all." - In such case your initial SQL was wrong, it just counted orders. You need something like

mysql_query("SELECT offer.oid, COUNT(solution.oid) FROM offer offer LEFT JOIN ON offer.oid = solution.oid WHERE offer.is_solved = 0 GROUP BY offer.oid ORDER BY offer.creation_time  DESC LIMIT".$interval_begin.",".$interval_end);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜