简体   繁体   English

在MySQL中为FIND_IN_SET

[英]FIND_IN_SET in mysql

I have a query that grabs info from a bunch of tables, including setting two columns to either 1 or 0 depending on the value of a field in another table; 我有一个查询,它从一堆表中获取信息,包括根据另一张表中字段的值将两列设置为1或0。 you can ignore the vast majority of it - I'm only concerned with the two IF lines: 您可以忽略其中的绝大多数-我只关心两条IF线:

SELECT DISTINCT CONCAT(np.first_name,' ',np.last_name) AS name, np.last_name, np.id, np.title, nc.web_name AS company, xsp.image_file AS image,

IF(prx.people_role_id IN(7,8),1,0) AS rfac,
IF(prx.people_role_id = 8,1,0) AS dfac

FROM expo_speaker xsp

LEFT JOIN expo_session_speaker xssx ON xssx.speaker_id = xsp.speaker_id
LEFT JOIN expo_session xss ON xss.session_id = xssx.session_id
LEFT JOIN new_people np ON np.id = xsp.people_id
LEFT JOIN people_role_xref prx ON prx.people_id = np.id
LEFT JOIN new_company nc ON np.company_id = nc.id

WHERE np.active = 1
AND xss.session_id = $sym->id
GROUP BY np.title
ORDER BY np.last_name

This worked just fine when each person could only have one role (represented by prx.people_role_id). 当每个人只能扮演一个角色时,这种方法就很好了(由prx.people_role_id表示)。 However, requirements changed recently, and each user can now have anywhere from zero to twelve different roles (and that number can change at any time.) 但是,需求最近发生了变化,每个用户现在可以拥有从零到十二个不同角色的任意位置(并且该数字可以随时更改。)

I've looked into find_in_set, but can't figure out how to combine it with the IN clause. 我已经研究过find_in_set,但无法弄清楚如何将其与IN子句结合使用。 I've tried group_concat(prx.people_role_id) , which gives me a comma-delimited list of all the roles assigned to a user. 我尝试了group_concat(prx.people_role_id),这给了我一个用逗号分隔的列表,其中列出了分配给用户的所有角色。 If there were only one role that we were looking for, it would be easy to use find_in_set to see if that role existed in the list of assigned roles. 如果只寻找一个角色,则可以很容易地使用find_in_set来查看该角色是否存在于分配的角色列表中。 But we have two possible roles for one of the IF statements. 但是,对于IF语句之一,我们有两种可能的作用。 How can I combine these functions (or any other) to determine if the group_concat column contains either 7 or 8? 如何合并这些函数(或任何其他函数)以确定group_concat列包含7还是8?

Got it; 得到它了;

IF((find_in_set(7, group_concat(prx.people_role_id))) OR (find_in_set(8, group_concat(prx.people_role_id))),1,0) AS rfac,
IF(find_in_set(8, group_concat(prx.people_role_id)),1,0) as dfac

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM