Mysql 获取具有一个匹配条件的行,如果没有匹配行,则获取所有行
我有一张简单的桌子Mysql 获取具有一个匹配条件的行,如果没有匹配行,则获取所有行,mysql,sql,select,where-clause,Mysql,Sql,Select,Where Clause,我有一张简单的桌子 **targeted_url_redirect targeted_countries msg_type non_targeted_url** http://new.botweet.com india,nepal,philippines NEW http://twisend.com http://expapers.com United States,Canada OLD http://all
**targeted_url_redirect targeted_countries msg_type non_targeted_url**
http://new.botweet.com india,nepal,philippines NEW http://twisend.com
http://expapers.com United States,Canada OLD http://all.twisend.com
https://tweeasy.com india,england OLD http://all.twisend.com
我在我的网站followrise.com上收到流量,我想根据上表中定义的国家/地区将用户重定向到特定的URL。我能够编写查询来获取存储在我的数据库中的来自目标国家的用户的行。但我正在寻找一种解决方案,如果目标国家/地区条件不返回任何行,则获取所有行
我写了下面的问题
SELECT * FROM tweeasy_website_redirection
WHERE message_type='OLD'
AND targeted_countries LIKE '%@country%'
如果游客来自印度、英国、美国、加拿大,这个查询会给我提供所需的行
但我希望,如果用户来自目标国家/地区列中未指定的国家/地区,则应获取所有第2行和第3行
如果需要将此表重新构造为2个或多个表以获得所需结果,请通知我。一个选项使用“不存在”:
当涉及到表的结构时:一个设计缺陷是将值列表存储为CSV列表。您应该有两个单独的表:一个用于存储URL,另一个用于存储URL和国家之间的1-N关系。比如:
table "url"
id targeted_url_redirect msg_type non_targeted_url
1 http://new.botweet.com NEW http://twisend.com
2 http://expapers.com OLD http://all.twisend.com
3 https://tweeasy.com OLD http://all.twisend.com
table "url_countries"
url_id country
1 india
1 nepal
1 philippines
2 united states
2 canada
3 india
3 england
选择*从简易网站重新定向
where targeted_countries not in in the stack where targeted_countries,如“%@country%”中选择targeted_countries。你能解释一下SELECT的含义吗1@prograshid:EXISTS仅检查是否存在满足条件的行;我们并不真正需要结果,我们可以使用SELECT 1放弃它们。这只是一种编码风格,SELECT*与SELECT NUL或SELECT“foo”是等效的。您应该修改模式,不要存储逗号分隔的列表。看见
table "url"
id targeted_url_redirect msg_type non_targeted_url
1 http://new.botweet.com NEW http://twisend.com
2 http://expapers.com OLD http://all.twisend.com
3 https://tweeasy.com OLD http://all.twisend.com
table "url_countries"
url_id country
1 india
1 nepal
1 philippines
2 united states
2 canada
3 india
3 england