1

this is MYSQL query question

First, let say we have

[ALL_MENU]

name
-----
pasta
pizza

and people ordered

ordered

customer name status              
john     pasta   delivered        
kim      pasta   delivered       
john     pizza   delivered        
john     pasta   delivered        

I want to go through the ordered table and find anyone who ordered all the menu

In this example, kim only ordered pasta so it should not be included but john ordered both pasta and pizza, so it should be included on the result.

is There any type of query to do the 'For loop' ability?

thank you

(ps, right now I only allow to use

some basic function command from mysql

group by , create view, exists , all, not exist , unique such and such )

=========================================================================

Ok, From the answer the count number of all menu thing is work when (customer,name) are the primary key But what if i added the data column, and primary key as (customer,name,data)

   customer name status              date
        john     pasta   delivered        3/4
        kim      pasta   delivered        3/5
        john     pasta   delivered        3/5

this is the new column i made john ordered the only pasta with 2 different date, but johns number of order count as 2.

so count method will not work for this

How do we fix this problem?

2
  • You could try GROUP_CONCAT mahmudahsan.wordpress.com/2008/08/27/… Commented Oct 30, 2013 at 2:25
  • If you do that, make sure to use an ORDER BY. Though IMHO GROUP_CONCAT isn't needed (or desirable). Commented Oct 30, 2013 at 2:28

1 Answer 1

2

The functionality of a for loop is a cursor. (FYI, most DBMS have such a construct.)

But never use a cursor when a plain old query will do just fine.

Here is one possible solution:

SELECT customer
FROM ordered
GROUP BY customer
HAVING COUNT(DISTINCT name) = (SELECT COUNT(*) FROM all_menu)

(This assumes that all names in ordered are found in all_menus, e.g. there is foreign key. If not, you'll have to add JOIN all_menu ON ordered.name = all_menu.name in the FROM clause.)

EDIT: "Simple"(!) commands only:

SELECT customer
FROM ordered o1
WHERE NOT EXISTS (
    SELECT * FROM all_menu
    WHERE name NOT IN (SELECT name FROM ordered o2 WHERE o1.customer = o2.customer)
)
Sign up to request clarification or add additional context in comments.

3 Comments

For now im only allowed to use simple commends, like exist,all,natural join etc.
Your "etc." leaves something to be desired. Which of GROUP BY, HAVING, DISTINCT, and COUNT are not simple "commands"?
I added a few more things on my question

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.