简体   繁体   English

mysql在表中两个字段之间的数组

[英]mysql where array between two fields in table

I have one table with offices that cover a range of postcodes with zipcode lowest and zipcode highest. 我有一张桌子,办公室里覆盖着邮政编码最低和邮政编码最高的一系列邮政编码。 Another table with zipcodes linked to a city name, 另一个带有邮政编码的表格与城市名称相关联,

The user searches for a city, and the database returns a array with each postcode linked to that city. 用户搜索城市,数据库返回一个数组,其中每个邮政编码都链接到该城市。 Then i want my code to use this array of postcodes to search in the offices table and see if any of the values fits between max and min value. 然后,我希望我的代码使用此邮政编码数组在office表中进行搜索,看看是否有任何值适合在最大值和最小值之间。

lets say we searched for a town that returned these zipcodes 可以说,我们搜索了一个返回这些邮政编码的城镇

 $search_string = 25002,25003,25004,25005,25006,25007,25008,25009,25013,25014,    25015,25018,25019,25022,25023,25024,25025,25053,25054,25100,25101,25106,25107,25108,25109,25110,25111,25112,25113,25114,25181,25183,25184

This was my attempt on a solution, thought it worked but apparently only workout for the first value. 这是我尝试的一种解决方案,以为它奏效了,但显然只有锻炼才能获得第一价值。

$query = $this->db->prepare("SELECT contacts.id FROM contacts INNER JOIN contacts_postcodes_links ON contacts_postcodes_links.contact = contacts.id WHERE contacts.id != 0 ".$category1." ".$category2." AND :search_string BETWEEN contacts_postcodes_links.minValue AND contacts_postcodes_links.maxValue ORDER BY id DESC ".$limit."");

So the part that i need help with, is it possible to do something like this? 因此,我需要帮助的部分是否可以做这样的事情? If not, how would i solve this problem? 如果没有,我将如何解决这个问题?

my_array BETWEEN contacts_postcodes_links.minValue AND contacts_postcodes_links.maxValue

Solved it by doing everything in the same query, 通过在同一查询中完成所有操作来解决此问题,

Added inner join on postcodes to the min and max values, and then filtered the postcodes city for the user input city string. 将邮政编码的内部联接添加到最小值和最大值,然后过滤用户输入的城市字符串的邮政编码城市。

Final result 最后结果

 $query = $this->db->prepare("SELECT DISTINCT(contacts.id) FROM contacts
                            INNER JOIN contacts_postcodes_links ON contacts_postcodes_links.contact = contacts.id
                            INNER JOIN postcodes ON postcodes.postcode >= contacts_postcodes_links.minValue AND postcodes.postcode <= contacts_postcodes_links.maxValue
                            WHERE contacts.id != 0 AND contacts.category_1 = :category_1 AND contacts.category_2 = :category_2
                            AND postcodes.city LIKE :search_string
                            ORDER BY id DESC LIMIT ".$options['limit']." OFFSET ".$options['start']."");

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

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