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

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

最佳答案

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

关于php - 如何将两个sql查询合并为一个具有可变限制的sql查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30733833/

相关文章:

php - 关于phpredis,我一直很困惑如何为我的PHP环境选择合适的分支

mysql - 如何对从联合查询收到的值进行独特的计数?

php - 从每种类型中选择 X 项

php - 将迭代次数转换为有限范围(如星期几)

mysql order by timestamp desc 限制范围不起作用

php - 在 MySQL 中查询速度快,但在 PHP 中查询速度慢

php - 我应该在哪里存储自定义 php 日志?

php - 如何在 PHP 中嵌入 YouTube 视频?

mysql - 无法删除 My Sql 中的表,您的 SQL 语法有错误 1064

mysql - 选择行并在同一查询中更新它们?