Question

I am trying to use if or case statement in mqsql.... here is my query

$db->query("SELECT 
keywords.keyword,
keywords.keyid,
sources.s_title,
sources.s_disc,
sources.sourceid,
sources.s_link
FROM link_ks
INNER JOIN keywords ON link_ks.keyid = keywords.keyid
INNER JOIN sources ON link_ks.sourceid = sources.sourceid
case when 
thumbsup_items.votes_up+thumbsup_items.votes_down != ''
then 
INNER JOIN thumbsup_items ON link_ks.sourceid = thumbsup_items.name
 else null
WHERE link_ks.keyid = :keyid
 order by 
if((thumbsup_items.votes_up+thumbsup_items.votes_down) != '',
((thumbsup_items.votes_up+thumbsup_items.votes_down) desc ,thumbsup_items.votes_up desc,sources.sourceid),
sources.sourceid )
");

I have used CASE and if Both is this query but nothing is working i know CASE and IF both are giving error but i dont know how to fix this ...

ERROR

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax

EDIT My problem is this. if there is no vote this query dont give any output so i am using IF statement

$db->query("SELECT 
keywords.keyword,
keywords.keyid,
sources.s_title,
sources.s_disc,
sources.sourceid,
sources.s_link
FROM link_ks
INNER JOIN keywords ON link_ks.keyid = keywords.keyid
INNER JOIN sources ON link_ks.sourceid = sources.sourceid
LEFT JOIN thumbsup_items ON thumbsup_items.votes_up+thumbsup_items.votes_down != '' AND link_ks.sourceid = thumbsup_items.name
WHERE link_ks.keyid = :keyid 
if((thumbsup_items.votes_up+thumbsup_items.votes_down) != '',
(thumbsup_items.votes_up+thumbsup_items.votes_down) desc ,
sources.sourceid )
");

Now Error in If statement ... Please help

Was it helpful?

Solution

Move the case inside the join condition, try this:

SELECT 
keywords.keyword,
keywords.keyid,
sources.s_title,
sources.s_disc,
sources.sourceid,
sources.s_link
FROM link_ks
INNER JOIN keywords ON link_ks.keyid = keywords.keyid
INNER JOIN sources ON link_ks.sourceid = sources.sourceid
LEFT JOIN thumbsup_items ON thumbsup_items.votes_up+thumbsup_items.votes_down != '' AND link_ks.sourceid = thumbsup_items.name
WHERE link_ks.keyid = :keyid
ORDER BY 
CASE
    WHEN (thumbsup_items.votes_up+thumbsup_items.votes_down) != ''
    THEN (thumbsup_items.votes_up+thumbsup_items.votes_down)
    ELSE sources.sourceid
END DESC

OTHER TIPS

You can't use a case or if to decide whether to include a join or not. Instead run the rest of the query with other joins and on the result set, use filter condition for the desired result.

In a SELECT statement, IF and CASE can only be used post joining of tables or views on columns or expressions. But you can't frame statement with a condition like

JOIN (CASE WHEN condition THEN this ELSE that END)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top