【问题标题】:what would be the Query in MS-Access for my following requirement?对于我的以下要求,MS-Access 中的查询是什么?
【发布时间】:2015-01-06 10:37:39
【问题描述】:

我想从产品表中获取所有具有最大产品 ID 的记录。产品表中的记录按类别存储,如下所示

Product id  Category id Product name    Product image
    1           1        product 1          path
    2           1        Product 2          path
    1           2        Product 1          path
    2           2        Product 2          path
    3           2        Product 3          path
    1           3        Product 1          path

我有如下类别表

类别 id 类别名称 1 类别 1 2 类别 2 3 类别 3

所以我需要编写查询来返回每个类别中最大产品的所有记录(在本例中为 1,2,3)所以我们会得到类似的结果

#    Product id  Category id Product name    Product image
1.       2           1        product 2          path
2.       3           2        product 2          path
3.       1           3        product 1          path

注意:- 产品 id 是主键,根据其类别生成 类别 id 是产品表中的外键。 我在我的 C# 应用程序中使用这个查询/数据库。我正在使用 MS-Access。

【问题讨论】:

  • 对不起,我无法绘制有问题的类似 sql 的表,请不要因此而否决这个问题
  • 请确认我的编辑符合您的意图。
  • @LasseV.Karlsen 非常感谢您重新格式化问题,非常感谢
  • 问题:为什么product 1在一行中显示为小写p而在另一行中显示为大写P?另一个问题:为什么列出的输出中的产品#3 的名称为product 2? (为什么Product 的输出是小写的?)这些只是错误吗?
  • 这只是一个记录盒没关系!(它可能是 PRODUCT 1 或 p 1 或 LAYS 或炸薯条或任何东西)我不明白你的第二个问题

标签: c# ms-access


【解决方案1】:

好的,这会有所帮助:

"SELECT * From Product WHERE Categoryid=(SELECT Max(Count(*)) from product group by Categoryid)"

【讨论】:

  • 就是上面提到的Product表中检索到的行(字段,记录)
  • 那么?你有什么想说的吗?
  • 那么一个是类别ID?
  • 是的,我提到过“Category”表,它有 2 个字段 Category_Id 和 Category_Name,它目前有 3 个类别 1,2,3
  • 喜欢类别 1 产品 ID 3 产品名称产品 1 及其路径?
【解决方案2】:

这应该有帮助

SQL Server -

select p.* from
(
   select max(productid) productid,categoryid from products group by categoryid
) a join products p on p.productid = a.productid
and p.categoryid = a.categoryid

访问 -

select [p].* from
(
   select max(productid) as pid,categoryid from products group by categoryid
) as [a] inner join [products] as [p] on [p].[productid] = [a].pid
and [p].categoryid = [a].categoryid

【讨论】:

  • 非常感谢您的回答,但此查询会引发语法错误:/(我认为这是因为别名 'a' 未定义或其他原因)
  • 是的,它在小提琴中运行良好,但是当我将它应用于我的访问数据库(查询设计)时,它会在 from 子句中引发语法错误。请注意,我有 2 个表格“产品”和“类别”,请帮忙(如果可以请给我的问题投票),非常感谢您抽出宝贵的时间
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-25
  • 2018-05-21
  • 2018-06-01
相关资源
最近更新 更多