MS ACCESS - 从没有表 1 id 重复项的 3 个表中检索行

问题描述

我一直在开发一个电子商务网站。

我想实现一项新功能,将产品与多个类别相关联。

谷歌搜索最好的数据库模式来实现这一点,我想出了 3 个表:

Table products
-----------------------------------------------------
id  | prod_name |    SEO    | promo_init | promo_end
-----------------------------------------------------
1   | Product 1 | product-1 | 2021/07/01 | 2021/07/31
2   | Product 2 | product-2 | 2021/07/01 | 2021/07/31
3   | Product 3 | product-3 | 2021/07/01 | 2021/07/31
4   | Product 4 | product-4 | 2021/08/01 | 2021/08/31

Table categories
---------------------------------------
id  |  cat_name  | SEO
---------------------------------------
1   | Category 1 | category-1
2   | Category 2 | category-2
3   | Category 3 | category-3

Table product_categories
---------------------------------------
id  | idprod | idcat
---------------------------------------
1   |    1   |   1
2   |    1   |   2
3   |    2   |   1
4   |    2   |   3
5   |    3   |   2
6   |    3   |   3

当然这些表有很多很多记录。

我需要的是显示促销中的产品,即插入表格中的最后 3 个产品。

到目前为止我有

select top 3 * from ((products PRODS
left join product_categories PC on PRODS.id=PC.idprod)
left join categories CATS on CATS.id=PC.idcat)
where PRODS.promo_init<=Date() and PRODS.promo_end>=Date()
order by PRODS.id desc

但此代码返回重复的产品:

PRODS.id | prod_name | PRODS.SEO | promo_init | promo_end  | PC.id | idprod | idcat | CATS.id |  cat_name  | CATS.SEO
3        | Product 3 | product-3 | 01/07/2021 | 31/07/2021 |   6   |    3   |   3   |   3     | Category 3 | category-3
3        | Product 3 | product-3 | 01/07/2021 | 31/07/2021 |   5   |    3   |   2   |   2     | Category 2 | category-2
2        | Product 2 | product-2 | 01/07/2021 | 31/07/2021 |   4   |    2   |   3   |   3     | Category 3 | category-3
2        | Product 2 | product-2 | 01/07/2021 | 31/07/2021 |   3   |    2   |   1   |   1     | Category 1 | category-1

我需要检索促销中的最后 3 个(不同)产品,我需要产品表中的所有字段和类别表中的所有字段。

正确的 sql 查询应该返回 ID 为 3,2 和 1 的产品。

有没有办法做到这一点?

感谢所有帮助!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)