简体   繁体   English

MYSQL-子查询问题

[英]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. 此查询返回所有演出者的ID_no,他们的姓氏和购买总数,但我想指定哪些购买是针对哪个演出者的。 Help in solving this would be greatly apprciated. 帮助解决此问题将不胜感激。

EDIT - DISTINCT(id_no) is redundant as it is a primary key. 编辑-DISTINCT(id_no)是多余的,因为它是主键。

This shows the number of sales for each artist_id: 这显示了每个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. 您应该使用GROUP BY来获得每个艺术家的人数。

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. PS:使用DISTINCT(id_no)是没有意义的,不仅因为id_no已经是唯一键,而且因为DISTINCT始终适用于选择列表中的所有列,即使您添加括号使其看起来像仅适用于一列的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM