如何将两个sql查询合并为一个具有可变限制的查询

时间:2015-06-09 13:44:44

标签: php mysql 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执行此操作的最优雅方法是什么?

2 个答案:

答案 0 :(得分:1)

我要加入:

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似乎建议

这是a fiddle

答案 1 :(得分:1)

稍微扩展 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