简体   繁体   中英

mysql select rows that have a same value as the last entered row

I have created a database that adds products to a basket/cart table.

What I want to do is check what was the last item added, and count how many times it item exists in the same table.

Say the table is called "basket" and the column is product.

eg:
cartid, product , user , date
1 , 50, bob , 2016-2-20 00:48:21
2 , 40, bob , 2016-2-20 00:48:23
3 , 50, bob , 2016-2-20 00:48:24
4 , 30, bob , 2016-2-20 00:48:25
5 , 40, bob , 2016-2-20 00:48:27

so in the above example, the last product is 40, and it occurs 2 times...

I was wondering if inner join to the same table is allowed.

SELECT product,
       count(product) AS total
FROM basket
WHERE `user` like 'bob' AND product =
    (SELECT product
     FROM basket b
     ORDER BY cartid DESC LIMIT 1)
GROUP BY product

DEMO

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