简体   繁体   中英

Access SQL Select value with more rows many to many relationship

I'm using Access for a cookbook database, an excercise for Uni.

I'm trying to make a query for a many-to-many relationship.

I have ricette and ingredienti tables, and a junction table named ricetta_ingrediente . Now I should make a query that retrieves each ricette associated with ingredienti used.

EDIT: Part of the question got deleted, I need to retrieve the recipe's ingredients of the one with the most ingredients used , it's the result I have to obtain.

Every single try got me either a syntax error or an empty result - how can I achieve this query?

MORE INFOS

The relationship schema

[ 1

I've tried to implement this suggestion , failing at it, how should it be?

Also here's my try and Access error :

[ 3]

Use the query builder DesignView to assist in building SQL statement. Result should look like:

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;

To retrieve recipe with the most ingredients as well as the ingredients, like:

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;

This will not resolve ties. All recipes with the number of ingredients matching the TOP 1 count will return. How should the query know you want only 1 and which one?

Your query is fine. You just need parentheses, because this is MS Access.

I would also use table aliases:

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;

EDIT:

For the revised question:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM