在mysql的某些条件下从两个表中获取数据

时间:2018-01-16 09:46:29

标签: mysql

我希望在两个表的country_of_origin相同或表中的country_of_origin等于Any Country时获取记录。

我使用了以下查询:

SELECT `tbui`.`user_id`,`tbui`.`first_name`,`tbui`.`last_name`,`tbui`.`education_level`,`tbui`.`sex`,`tbui`.`country_of_origin`,`tbui`.`city`,`tbui`.`state`,`tbui`.`country`,`tbui`.`occupation`,`tbui`.`about`,TIMESTAMPDIFF(YEAR,`tbui`.`age`,CURDATE()) as age
FROM `tb_preference_dropdown` as `tbpda`
LEFT JOIN `tb_user_answers` as `tbua` ON `tbpda`.`question_id` = `tbua`.`question_id`
LEFT JOIN `tb_preference_questions` as `tbpa` ON `tbpda`.`user_id` = `tbpa`.`user_id`  
LEFT JOIN `tb_user_info` as `tbui` ON `tbua`.`user_id` = `tbui`.`user_id`
WHERE `tbpda`.`user_id` = $uid 
AND TIMESTAMPDIFF(YEAR,`tbui`.`age`,CURDATE()) >=`tbpa`.`min_age_required` AND TIMESTAMPDIFF(YEAR,`tbui`.`age`,CURDATE()) <= `tbpa`.`max_age_required`
AND IF(`tbui`.`country_of_origin` != 'Any Country',`tbui`.`country_of_origin` = `tbpa`.`country_of_origin`,true)
AND `tbua`.`user_id` != $uid
AND `tbui`.`user_id` NOT IN ($matches)
AND `tbui`.`user_id` NOT IN ($block_users)
AND `tbui`.`user_id` NOT IN ($reported_user)
AND `tbui`.`sex` != '$gender'
AND IF($count > 0,`tbui`.`country` IN ($result),true)
GROUP BY  `tbui`.`user_id`

这个工作正常,两个表的国家/地区名称相同但country_of_origin = 'Any Country'

时没有获取记录

由于

1 个答案:

答案 0 :(得分:1)

if返回一个值,而不是要计算的新条件。

因此,在您的代码中,除非truefalse,否则您将始终获得布尔值tbui.country_of_origin != 'Any Country'true

where中,你必须使用:

WHERE tbui.country_of_origin = 'Any Country' OR tbui.country_of_origin = tbpa.country_of_origin

您可能还想检查tbpa.country_of_origin = 'Any country'