简体   繁体   中英

MYSQL - Issue with sub-query

SELECT DISTINCT(id_no), lastname,
    (SELECT COUNT(purchasedate)  num_of_purch
    FROM sales JOIN Artist ON
        sales.id = Artist.id_no
        WHERE  DATE_SUB(CURDATE(),INTERVAL 1
                          YEAR) <= purchasedate 
              ) AS num_of_purch

FROM Artist 

This query returns the all Artist's ID_no, and their last name and the total number of purchases, altho i want to specify which purchases were to which artist. Help in solving this would be greatly apprciated.

EDIT - DISTINCT(id_no) is redundant as it is a primary key.

This shows the number of sales for each artist_id:

SELECT artist.id_no, count(sales.id) as num_of_purch
FROM artist left join sales on sales.id = artist.id_no
WHERE DATE_SUB(CURDATE(), INTERVAL 1 YEAR) <= purchasedate
GROUP BY artist.id

To return also the last names, and all of the details:

SELECT art_tot.id_no, art_tot.lastname, art_tot.num_of_purch, sales.*
FROM (SELECT artist.id_no, artist.lastname, count(sales.id) as num_of_purch
      FROM artist left join sales on sales.id = artist.id_no
      WHERE DATE_SUB(CURDATE(), INTERVAL 1 YEAR) <= purchasedate
      GOUP BY artist.id, artist.lastname) art_tot
      left join sales on art_tot.id_no = sales.id

This should give you artist and number of purchases per artist

select a.id_no, a.lastname, count(s.purchasedate) num_of_purch
from artists a
join sales s on a.id_no = s.id
where date_sub(curdate(), interval 1 year) <= s.purchasedate
group by a.id_no, a.lastname

You should use a GROUP BY to get the count per artist.

And you should use an outer join to include artists who have no sales within the last year.

SELECT a.id_no, a.lastname, COUNT(s.purchasedate) AS num_of_purch
FROM Artist a
LEFT OUTER JOIN sales s ON s.id = a.id_no
  AND s.purchasedate => CURDATE() - INTERVAL 1 YEAR
GROUP BY a.id_no;

PS: Using DISTINCT(id_no) is meaningless not only because id_no is already a unique key, but because DISTINCT always applies to all columns in the select list, even if you add parentheses to make it look like a function that applies only to one column.

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