tags:

views:

27

answers:

1

My query is this

SELECT C.id, C.title, C.short_description,C.rating,C.image,C.duration,C.difficulty ,  
0 AS active , if(G.theme_id = 3,1,0) as orderField
FROM tblIdeas C
INNER JOIN tblIdeas_themes G on (G.Idea_id = C.id )
AND C.category_id = 2  and C.published = 1 and C.DELETED=0 and C.id != 4 
ORDER BY active DESC , orderField DESC ,title ASC

 tblideas ------ id,description , etc
    tblideas_themes    -------- idea_id , theme_id
    tblthemes -------------id , theme_name

in tblideas_themes i have one idea with multiple themes.

I want that if idea belong to particular theme then order field should be one and if not the orderfield should be 0

The problem is i am getting duplicate rows e,g

Idea 1 ---------- with orderField 1 --as it was in that theme
Idea 1 -----------with order field 0 as ---it was also in the other theme as well

I want that there should be only one idea in the list.

If the idea belongs to more than one theme then i want get that row which belongs to that theme with orderfield =1 . but if idea does not belong to that theme , then i want to get any other row with orderfield = 0

+1  A: 

You can reduce the rows to one row per idea with GROUP BY.

Use an OUTER JOIN to join to the themes table, and add the theme_id=3 condition to the join expression. So if a theme with theme_id=3 is found, the orderField will be 1. If no theme with theme_id=3 is found, then it'll be null because of the outer join, and orderField will default to 0.

SELECT C.id, C.title, C.short_description, C.rating, C.image, C.duration, 
    C.difficulty, 0 AS active, IF(G.theme_id = 3,1,0) as orderField
FROM tblIdeas C
LEFT OUTER JOIN tblIdeas_themes G ON (G.Idea_id = C.id AND G.theme_id = 3)
WHERE C.category_id = 2  and C.published = 1 and C.DELETED=0 and C.id != 4 
GROUP BY C.id
ORDER BY active DESC , orderField DESC ,title ASC
Bill Karwin
For eg i have two rows with orderField 1 and 0 . If i use group by which field will mysql keep. i mean i don't want that mysql selects the row with 0 orderField
Mirage
I tried that and it eleiminates the idea with orderField 1. If i can somehow keep the row with orderfield 1 then i am done
Mirage
You can't have both orderField 1 and 0 within a given group. Either the join finds themes with theme_id=3 in which case orderField is 1. Or else the join finds no themes with them_id=3, so theme_id is null, which makes orderField 0.
Bill Karwin
Is there any other way to get that , may you can chnage the query to get what i want
Mirage
Maybe I don't understand what you're asking for, because as I read your question, this does produce the result you're asking for.
Bill Karwin
It does produce the result but it removed the row with orderField 1 but i want only the row with oderField 1 and if there is no row With orderField 1 and it can keep any row with OrderField 0
Mirage
Thanks buddy it worked , but didn'y fully understood why it worked
Mirage