MYSQL select items with twice or more instance in a table
Filed Under (mysql) by admin on 10-12-2009
Tagged Under : mysql
Lets say we have this table the ORDERS TABLE
ID customer ordered
—————————-
1111 – John – pizza
2222 – Pete – salad
3333 – Rach – pizza
4444 – Maxx – pizza
5555 – Zigg – rice
1212 – Vinc – salad
4545 – Grac – sushi
1313 – Mark – cake
2424 – Phils – salad
We only want to show items which has been ordered more than 2 times here is our query
—————————————————————————————————————————
SELECT *,count(ordered) as cnt FROM ORDERS group by ordered having cnt > 2
—————————————————————————————————————————-
result:
1111 – John – pizza
3333 – Rach – pizza
4444 – Maxx – pizza
2222 – Pete – salad
1212 – Vinc – salad
2424 – Phils – salad
We use here the having keyword
note: having will work if you have group by on your query


