简体   繁体   中英

Select from mysql database where columns contains PHP

I have a database and some of the columns contain things like CA, GB etc, although some contain multiple country codes like

US+GB+CA+AU

I'm just wondering what kind of query I would do that would return that row when I'm searching for just CA or just GB, and no necessarily the whole package US+GB+CA+AU

Encase that's a little confusing, basically I just need to return that row based on a search for just CA or just GB etc.

Thanks

Use FIND_IN_SET() , but you'll first need to replace + with , since it expects a comma-separated string. Even without the REPLACE() , this is will not make use of any index on the countrycodes column.

SELECT * FROM tbl 
WHERE FIND_IN_SET('AU', REPLACE(countrycodes, '+', ',')) > 0

The proper long term solution, however, is to change your database structure to normalize these country codes into a table that contains only two columns - a country code, and the id of the associated row from the table you're attempting to query now. You can then index the column appropriately to improve performance (possibly drastically improve it).

I would recommend to normalise it like liquorvicar said.

but using SELECT ... WHERE countrycode LIKE '%GB%' would work. http://w3schools.com/sql/sql_like.asp

It's not a good solution, but you can use LIKE for your query:

SELECT * FROM `table` WHERE `field` LIKE '%+CA+%' OR `field` LIKE 'CA+%' OR `field` LIKE '%+CA' OR `field` = 'CA'

Last two checks for firs and last values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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