MySQL查询高级搜索多个条件

时间:2014-10-08 16:41:20

标签: php mysql search

我正在使用高级搜索查询,用户根据多个条件选择复选框。我是初学者,所以我希望能找到我是否走在正确的轨道上。我知道查询很乱。

编辑:我意识到这需要两个问题,所以我已经修改为严格的查询问题

表格数据

Table ss_users
user_id  first_name   last_name   admin_level   user_approved  
1        nick         jones       0             1      
2        johnny       rocket      0             1      

Table ss_user_profile_status
user_id  photo_uploaded   
1        1
2        1

Table ss_user_photos
photo_id  user_id  filename      selected
1         1        photo_1.jpg   1
2         2        photo_2.jpg   0
3         2        photo_2.jpg   1

Table ss_general
user_id  city        state      zip     neighborhood
1        baltimore   maryland   00125   hamsterdam
2        lakeland    maine      11542   treemont

Table ss_languages
user_id  french  german  italian  spanish
1        0       1       0        1
2        0       0       1        1

Table ss_experience
user_id  waldorf  kumon  homeschooling 
1        0       1       0
2        0       0       1

我目前的结果是所有用户,不应该是这种情况:

SELECT 
    ss_users.*, ss_user_profile_status.*, ss_user_photos.*, ss_general.*, 
    ss_languages.*, ss_experience.*, ss_users.user_id AS userID, 
    ss_user_profile_status.user_id, ss_languages.user_id AS langID
FROM 
    ss_users
JOIN 
    ss_user_profile_status ON ss_users.user_id = ss_user_profile_status.user_id
LEFT JOIN 
    ss_user_photos ON ss_users.user_id = ss_user_photos.user_id
AND 
    ss_user_photos.selected = 1
LEFT JOIN 
    ss_languages ON ss_users.user_id = ss_languages.user_id
LEFT JOIN 
    ss_general ON ss_users.user_id = ss_general.user_id
LEFT JOIN 
    ss_experience ON ss_users.user_id = ss_experience.user_id
WHERE 
    ss_users.user_id = ss_user_profile_status.user_id 
AND 
    ss_general.neighborhood_select LIKE '%hamsterdam%'
OR 
    ss_languages.spanish = 1
OR 
    ss_experience.kumon = 1
AND 
    ss_users.sitter_approved = 1
AND 
    ss_users.admin_level = 0
GROUP BY 
    ss_users.user_id DESC

对于输出,我需要表示大部分用户配置文件,这就是我选择大量表格数据以及额外连接的原因。

1 个答案:

答案 0 :(得分:2)

为你的大胖SQL选择

SELECT 
    ss_users.*, ss_user_profile_status.*, ss_user_photos.*, ss_general.*, 
    ss_languages.*, ss_experience.*, ss_users.user_id AS userID, 
    ss_user_profile_status.user_id, ss_languages.user_id AS langID
FROM ss_users
    JOIN ss_user_profile_status ON ss_users.user_id = ss_user_profile_status.user_id
    LEFT JOIN ss_user_photos ON ss_users.user_id = ss_user_photos.user_id AND ss_user_photos.selected = 1
    LEFT JOIN ss_languages ON ss_users.user_id = ss_languages.user_id
    LEFT JOIN ss_general ON ss_users.user_id = ss_general.user_id
    LEFT JOIN ss_experience ON ss_users.user_id = ss_experience.user_id
WHERE 
    ( ss_general.neighborhood_select LIKE '%hamsterdam%' OR ss_languages.spanish = 1 OR ss_experience.kumon = 1 ) AND ss_users.sitter_approved = 1 AND ss_users.admin_level = 0

我只编辑一些地方,例如在OR周围添加括号并删除第一个条件,因为它似乎是多余的,并且还删除了组,因为它会留下一些数据