我的查询是
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
在tblideas_themes中我有一个有多个主题的想法。
我希望如果想法属于特定主题,则订单字段应为1,否则订单字段应为0
问题是我得到重复的行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
我希望列表中只有一个想法。
如果这个想法属于多个主题,那么我想要获得属于该主题的行,其中orderfield = 1。但如果想法不属于那个主题,那么我想得到orderfield = 0
的任何其他行答案 0 :(得分:0)
您可以使用GROUP BY将每个想法的行减少到一行。
使用OUTER JOIN加入主题表,并将theme_id = 3条件添加到连接表达式。因此,如果找到theme_id = 3的主题,orderField将为1.如果找不到theme_id = 3的主题,那么由于外连接它将为null,orderField将默认为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