简体   繁体   中英

SELECT and SELECT COUNT in two tables in mySQL

is it possible to combine SELECT and SELECT COUNT in two tables that are connected with the argument JOIN?

I want to select first and last name of customers and only count the amount of orders for each customer.

The table should display first-, lastname and the amount of orders for each customer, whereas last column should be named 'Anzahl Aufträge'.

enter image description here

enter image description here

I just added two links, so you can see, how the table should look like. :)

You have not given details so I must guess.

Try this:

       SELECT customer.customer_id, customer.givenname, customer.surname, 
              COUNT(*) number_of_orders
         FROM customer
         JOIN order ON customer.customer_id = order.customer_id
        GROUP BY customer.customer_id, customer.givenname, customer.surname

I think you are mean this:

SELECT firstName, lastName, cnt
FROM (
   SELECT customer_id, count(*) as cnt
   FROM orders
   GRUP BY customer_id
) AS q1
INNER JOIN customers as c on c.customer_id = q1.customer_id

You need a group by to collapse the orders to the customer level:

SELECT first_name, last_name, COUNT (*)
FROM customers JOIN orders
ON customers.id = orders.customer_id
GROUP BY customers.id;

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