如何获取与IN()运算符中的所有值关联的记录

时间:2015-01-21 13:36:08

标签: mysql sql

我想获取与数组中所有值相关联的记录。但问题是,如果db中存在IN()中的任何一个值,则查询将获取记录。如果所有值都为真,我想获取记录。

SELECT J.ID , J.U_POST_ID,
       J.TITLE,J.CREATION_DATE,J.STATUS,
       R.FIRST_NAME, R.LAST_NAME,R.CLINICAL_CLINIC_NAME,
       J.REQUIREMENT,J.STATE,J.CITY,J.DESCRIPTION,
       J.CALL_DUR,J.USER_ID
FROM  df_job_meta M 
    LEFT OUTER JOIN df_job_post J ON M.JOB_ID = J.ID
    LEFT OUTER JOIN df_register_users R ON R.ID = J.USER_ID
WHERE
    J.STATUS='ACTIVE' AND 
    R.OCCUPATION !='student' AND 
    J.STATE IN ('Maharashtra') AND 
    J.CITY IN ('Nagpur') and  
    M.VALUE IN ('Clinical','Fresher','BDS Intern','Full Time')

表df_job_meta

---------------------------------------------
***VALUE***       |  **META_KEY**  |  JOB_ID 
--------------------------------------------
-----------------------------------------
Part Time         | work_hour      | 103
-------------------------------
BDS Intern        |qualification   | 103
----------------------------------------
Clinical          |profile         | 103
----------------------------------------
1                 |num_vacancy     | 103 
----------------------------------------
1 to 3 Years      |experience      | 103

--------------------------------------

1 个答案:

答案 0 :(得分:0)

我认为您需要生成一些动态SQL。对于您给出的编码值集合:

SELECT J.ID , J.U_POST_ID,
   J.TITLE,J.CREATION_DATE,J.STATUS,
   R.FIRST_NAME, R.LAST_NAME,R.CLINICAL_CLINIC_NAME,
   J.REQUIREMENT,J.STATE,J.CITY,J.DESCRIPTION,
   J.CALL_DUR,J.USER_ID
FROM (
    SELECT M1.ID
    FROM df_job_meta M1
       INNER JOIN df_job_meta M2 ON M1.JOB_ID = M2.JOB_ID
       INNER JOIN df_job_meta M3 ON M1.JOB_ID = M3.JOB_ID
       INNER JOIN df_job_meta M4 ON M1.JOB_ID = M4.JOB_ID
    WHERE M1.VALUE = 'Clinical'
        AND M2.VALUE = 'Fresher'
        AND M3.VALUE = 'BDS Intern'
        AND M4.VALUE = 'Full Time'
) as JOBS_MATCHING_META
    LEFT OUTER JOIN df_job_post J ON M.JOB_ID = J.ID
    LEFT OUTER JOIN df_register_users R ON R.ID = J.USER_ID
WHERE
    J.STATUS='ACTIVE' AND 
    R.OCCUPATION !='student' AND 
    J.STATE IN ('Maharashtra') AND 
    J.CITY IN ('Nagpur')
;

(未测试的)

我会注意到查看df_job_meta的示例数据是否也需要查看META_KEY列 - 即该值仅在正确的情况下才有效,例如

WHERE M1.META_KEY = 'qualification' AND M1.VALUE = 'BDS Intern'

作为最后的观察,看起来yuo正试图实施某种形式的分面搜索;也许值得看一些直接实现它的替代数据存储?