我正在为网站创建简单的横幅跟踪代码。这可以正常工作,但是两个客户端在随机查询中占主导地位,因为它们在此位置具有多个横幅。有时,他们会显示出三分之二或三分之三的信息,这并不是客户想要的。这是我当前对该视图的查询。
SELECT * FROM banners
WHERE location like '["2"]'
AND published = '1'
ORDER BY rand()
LIMIT 3;
我还有一个名为client的字段。我只想在其位置与“ [“ 2”]'相匹配的时间内选择其中一个横幅。预先感谢。
| published | location | client | img |
|-----------|----------|---------|---------------------|
| 1 | ["2"] | ClientA | /banners/image1.jpg |
| 1 | ["2"] | ClientA | /banners/image2.jpg |
| 1 | ["2"] | ClientA | /banners/image3.jpg |
| 1 | ["2"] | ClientB | /banners/image4.jpg |
| 1 | ["2"] | ClientC | /banners/image5.jpg |
| 1 | ["2"] | ClientD | /banners/image6.jpg |
答案 0 :(得分:1)
使用您的示例:
create table banners (
published int,
location varchar(10),
client varchar(10),
img varchar(100)
);
insert into banners values
(1, '["2"]', 'ClientA', '/banners/image1.jpg'),
(1, '["2"]', 'ClientA', '/banners/image2.jpg'),
(1, '["2"]', 'ClientA', '/banners/image3.jpg'),
(1, '["2"]', 'ClientB', '/banners/image4.jpg'),
(1, '["2"]', 'ClientC', '/banners/image5.jpg'),
(1, '["2"]', 'ClientD', '/banners/image6.jpg');
您可以使用的一种方法是使用这种方法:
-- we'll use a temporary table to store some data
-- if that table exists, let's drop it first.
-- you can change the name from banners_007 to something else
drop table if exists banners_007;
-- create that table to store data temporarily
-- store all data from banners and add a random number to each row
create table if not exists banners_007 as
select *, rand() as randomnumber from banners;
-- get client and the lowest random number
-- and get all records for that client (you'll get 1 record per client)
-- order those clients randomly
-- get the top 3 records
select a.* from banners_007 a
inner join (
select client, min(randomnumber) as min_rn
from banners_007
group by client
) b on a.client = b.client and a.randomnumber = b.min_rn
order by rand()
limit 3;