I need assistance with my MySql query (selecting from multiple tables)

Bojan

So, I have 3 tables:

  1. PIZZA with pizza_ID, pizza_title, and pizza_price
  2. INGREDIENTS with ingredients_ID; ingredients_title, and ingredients_description
  3. PIZZA_INGREDIENTS with ID, pizza_id, ingredients_id

and I need to select all pizza_title from PIZZA that contains 2 ingredients. For now, I have this:

SELECT pizza.pizza_ID, pizza.pizza_title, pizza.pizza_price, pizza_ingredients.ingredient_id
FROM pizza
JOIN pizza_ingredients ON pizza_ingredients.pizza_id=pizza.id
WHERE pizza_ingredients.ingredient_id='7' or pizza_ingredients.id='4'
GROUP BY pizza.id

this code returns all pizzas that have ingredient 7 or ingredient 4. and I need only pizzas that have both 7 and 4...

SQL is not my strong side, and I appreciate any help. Thanks

Tim Biegeleisen

Try joining to a subquery which does an aggregation to find all pizzas having exactly two ingredients:

SELECT p1.*
FROM pizza p1
INNER JOIN
(
    SELECT pizza_id
    FROM pizza_ingredients
    GROUP BY pizza_id
    HAVING COUNT(*) = 2
) p2
    ON p1.pizza_id = p2.pizza_id;

If I misunderstood the wording of your question, and you instead want to find all pizzas having two particular ingredients, without regard to other ingredients, then use this query:

SELECT p1.*
FROM pizza p1
INNER JOIN
(
    SELECT pizza_id
    FROM pizza_ingredients
    WHERE ingredients_id IN (4, 7)
    GROUP BY pizza_id
    HAVING COUNT(DISTINCT ingredients_id) = 2
) p2
    ON p1.pizza_id = p2.pizza_id;

Эта статья взята из Интернета, укажите источник при перепечатке.

Если есть какие-либо нарушения, пожалуйста, свяжитесь с[email protected] Удалить.

Отредактировано в
0

я говорю два предложения

0обзор
Войти в системуУчаствуйте в комментариях

Статьи по теме

Selecting from multiple tables in laravel

selecting N particular tables from MySQL

How to query multiple tables in mysql

I need assistance with variables in classes

I need Assistance with my Function Problem, I am getting zero for all my answers

SQL Query - Need some assistance with a query

Database query from multiple tables

PHP MySQL Selecting Multiple Tables Based on Column/Row Value

How to UPDATE multiple tables with 1 query in MYSQL

I got 3 tables and I need some query

I need to take form data from react, and post it to my server to use as my query variable. What am I doing wrong?

Query fields from different mysql tables

MySQL query to get the total from three tables

MYSQL Combing Two tables From Multiple Row

Need assistance with PHP and my HTML5 form

How can I query mulltiple tables and order by date in my view

Query! how can i get total meals and cost from three tables for each user! This is my first question so sorry for the inconvenience

Query chaining multiple tables

How can I check if row exists in multiple tables with one query?

How can I query multiple tables relationship in SQLalchemy?

How to count rows from multiple tables in one single sql query

SQL query to select from multiple tables and create third table

Joining multiple tables in MySQL

Querying multiple tables on MySQL

I need help joining tables

I want to fetch list of tables from mysql database from nodejs

How to delete from multiple tables with the same column in mysql?

Mysql select rows from multiple tables in specific order

Will I need to do a join of 4 tables to fulfill this SQL query or is there a simpler method?

TOP список

  1. 1

    Распределение Рэлея Curve_fit на Python

  2. 2

    How to click an array of links in puppeteer?

  3. 3

    В типе Observable <unknown> отсутствуют следующие свойства из типа Promise <any>.

  4. 4

    Как добавить Swagger в веб-API с поддержкой OData, работающий на ASP.NET Core 3.1

  5. 5

    Нарисуйте диаграмму с помощью highchart.js

  6. 6

    无法通过Vue在传单中加载pixiOverlay

  7. 7

    Отчеты Fabric Debug Craslytic: регистрация, отсутствует идентификатор сборки, применить плагин: io.fabric

  8. 8

    Статус HTTP 403 - ожидаемый токен CSRF не найден

  9. 9

    TypeError: store.getState não é uma função. (Em 'store.getState ()', 'store.getState' é indefinido, como posso resolver esse problema?

  10. 10

    ContentDialog.showAsync в универсальном оконном приложении Win 10

  11. 11

    В UICollectionView порядок меняется автоматически

  12. 12

    Merging legends in plotly subplot

  13. 13

    Elasticsearch - Нечеткий поиск не дает предложения

  14. 14

    Bogue étrange datetime.utcnow()

  15. 15

    Объединение таблиц в листе Google - полное соединение

  16. 16

    Single legend for Plotly subplot for line plots created from two data frames in R

  17. 17

    как я могу удалить vue cli 2?

  18. 18

    ViewPager2 мигает / перезагружается при смахивании

  19. 19

    Компилятор не знает о предоставленных методах Trait

  20. 20

    JDBI - В чем разница между @define и @bind в JDBI?

  21. 21

    проблемы с AVG и LIMIT SQL

популярныйтег

файл