[英]Get random record from database table with multiple checks in mysql?
I have database table named ' ads
'.i want to show these ads on the the websites randomly.My table structure is 我有一个名为' ads
'的数据库表。我想在这些网站上随机显示这些广告。我的表结构是
user_id int(11)
type varchar(50)
title varchar(100)
body varchar(100)
display_url varchar(100)
target_url varchar(100)
dimension varchar(50)
image varchar(200)
preferred_countries text
preferred_languages text
preferred_sites text
excluded_sites text
preferred_keywords text
excluded_keywords text
preferred_devices varchar(100)
schedule mediumtext
clicks int(20)
clicked int(11)
cpc decimal(20,20)
As you can see there are columns like preferred_countries
, preferred_languages
, preferred_devices
etc. I want to show these ads to a visitor by applying multiple checks like if there is prefered country for any ad then it will be shown to the visitor of that specific country and so on. 如您所见,存在诸如preferred_countries
, preferred_languages
, preferred_devices
等列。我想通过应用多次检查来向访问者展示这些广告,例如是否有针对任何广告的首选国家/地区,然后将其显示给该特定国家/地区的访问者,以此类推。 I have fetched all the data related to user ie. 我已经获取了所有与用户有关的数据。 visitor's country, visitor's language etc 访客所在国家,访客语言等
But i am not getting any idea how to fetch the records like this. 但是我不知道如何获取这样的记录。
select * from ads
where preferred_countries = $mycountry
order by rand()
limit 1
try this 尝试这个
select * from ads
where preferred_countries = $mycountry and preferred_languages=$language
order by rand()
limit 1
You could consider MySQL's RAND() function combined with an ORDER BY FIELD() 您可以考虑将MySQL的RAND()函数与ORDER BY FIELD()结合使用
SELECT * FROM `ads`
ORDER BY FIELD(preferred_countries, '$mycountry') DESC, RAND()
LIMIT 1
This won't filter out rows that don't match $mycountry, but if they exist, you'll get them first. 这不会筛选出与$ mycountry不匹配的行,但是如果它们存在,您将首先获得它们。 You should also get a random result if there is more than one match. 如果有多个匹配项,您还应该获得随机结果。
Of course this won't work as well if your preferred_countries field might contain multiple country names. 当然,如果您的preferred_countries字段可能包含多个国家/地区名称,那么这将无法正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.