[英]How to merge two sql queries into one with variable limit
我有两个表:
user_favourites -> id, user_id, product_id
product -> id, title, bought
如果用户的收藏夹少于9个,我需要显示9个结果->用户收藏夹以及其他产品。
因此,在我的页面上应该显示9个产品。 如果用户选择了9个最喜欢的产品,那么我将显示这9个最喜欢的产品,如果他选择的少于9个(至少说5个),那么我必须显示系统中他的最喜欢的5个产品和4个评分最高的产品。
为了获得用户的收藏夹,我有这个查询:
select product_id from user_favourites where user_id = $userId
为了获得最高评价的产品,我有以下查询:
select id, title, count(bought) from product group by id limit 9
因此,如果用户未选择9,则由于我想显示最喜欢的产品+最受欢迎的产品,是否可以将这两个查询合并为一个以获得所需结果? 请不要在这里出现一个问题,我需要删除重复项。 如果用户选择ID为999的产品,但他也是最受欢迎的产品之一,那么我只需要显示一次即可。 我还需要获得9个结果的最大值。
使用php和mysql做到这一点的最优雅的方法是什么?
我会参加:
select P.id, P.title, P.bought
from product as P
left join user_favourites as UF on(P.id=UF.product_id)
where UF.user_id=$user_id OR UF.user_id IS NULL
order by user_id DESC
limit 9;;;
假设在product
表中每个产品有1行购买的是整数,而不是每个买方1行,因为您的group by
似乎暗示
这是一个小提琴
对dirluca的精美作品稍作扩充
create table product
(
id int not null auto_increment primary key, -- as per op question and assumption
title varchar(255) not null,
bought int not null -- bought count assumption, denormalized but who cares for now
);
create table user_favourites
(
id int not null auto_increment primary key, -- as per op question and assumption
user_id int not null,
product_id int not null,
unique index (user_id,product_id)
-- FK RI left for developer
);
insert into product (title,bought) values ('He Bought 666',10),('hgdh',9),('dfhghd',800),('66dfhdf6',2),('He Bought this popular thing',900),('dfgh666',11);
insert into product (title,bought) values ('Rolling Stones',20),('hgdh',29),('4dfhghd',100),('366dfhdf6',2),('3dfghdgh666',0),('The Smiths',16);
insert into product (title,bought) values ('pork',123),('and',11),('beans',16),('tea',2),('fish',-9999),('kittens',13);
insert into user_favourites (user_id,product_id) values (1,1),(1,5);
select P.id, P.title, P.bought,
( CASE
WHEN uf.user_id IS NULL THEN 0 ELSE -1 END
) AS ordering
from product as P
left join user_favourites as UF on(P.id=UF.product_id)
where UF.user_id=1 OR UF.user_id IS NULL
order by ordering,bought desc
limit 9;
-当放入gui时,自然会忽略排序列
id title bought ordering
5 He Bought this popular thing 900 -1
1 He Bought 666 10 -1
3 dfhghd 800 0
13 pork 123 0
9 4dfhghd 100 0
8 hgdh 29 0
7 Rolling Stones 20 0
12 The Smiths 16 0
15 beans 16 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.