[英]Access SQL Select value with more rows many to many relationship
我正在将Access用于菜谱数据库,这是Uni的练习。
我正在尝试查询多对多关系。
我有ricette
和ingredienti
表,并命名为结合表ricetta_ingrediente
。 现在,我应该进行一个查询,以检索与所用成分相关的每个小米饭。
编辑:部分问题被删除,我需要检索使用最多配料的食谱的配料,这是我必须获得的结果。
每次尝试都会使我出现语法错误或空结果-如何实现此查询?
更多信息
关系架构
[
我尝试实施此建议 ,但未成功,应该怎么做?
这也是我的尝试和访问错误:
[
使用查询生成器DesignView可以帮助构建SQL语句。 结果应如下所示:
SELECT ricette.nome, ingredienti.nome
FROM ingredienti
RIGHT JOIN (ricette RIGHT JOIN ricetta_ingrediente
ON ricette.ID = ricetta_ingrediente.id_ricetta)
ON ingredienti.ID = ricetta_ingrediente.id_ingrediente;
要检索包含最多成分的配方,例如:
SELECT TOP 1 ricette.nome, ingredienti.nome
FROM (SELECT id_ricetta, Count([id_ingrediente]) AS CountIng
FROM ricetta_ingrediente GROUP BY id_ricetta) AS Q1
RIGHT JOIN (ricette RIGHT JOIN (ingredienti RIGHT JOIN ricetta_ingrediente
ON ingredienti.ID = ricetta_ingrediente.id_ingrediente)
ON ricette.ID = ricetta_ingrediente.id_ricetta)
ON Q1.id_ricetta = ricetta_ingrediente.id_ricetta
ORDER BY Q1.CountIng DESC;
这不会解决关系。 所有配料数量与TOP 1计数匹配的配方将返回。 查询应如何知道您只想要1,而又只想要哪个?
您的查询很好。 您只需要括号,因为这是MS Access。
我还将使用表别名:
SELECT r.nome, i.nome
FROM (ricette as r INNER JOIN
ricetta_ingrediente as ri
ON r.ID = ri.id_ricetta
) INNER JOIN
ingredienti as i
ON i.ID = ri.id_ingrediente;
编辑:
对于修订后的问题:
SELECT TOP (1) r.nome
FROM (ricette as r INNER JOIN
ricetta_ingrediente as ri
ON r.ID = ri.id_ricetta
) INNER JOIN
ingredienti as i
ON i.ID = ri.id_ingrediente
GROUP BY r.nome
ORDER BY COUNT(*) DESC;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.