如何用JOIN和WHERE创建一个查询,或者如何让它们成为朋友?

问题描述 投票:0回答:1

我需要建立一个查询,其中有客户的名字和他们每个月的订单列,有些客户在某些月份没有订单,那里的字段必须是0.问题是,当我在一个查询中使用WHERE和OUTER JOIN(不管是哪一个)*,必须有0`s被WHERE切断。那么如何解决这个问题呢?

表的描述符被钉住了。

SELECT name
     , ordering.id_client
     , COUNT(order_date) 
  FROM ordering 
 RIGHT 
 OUTER 
  JOIN client 
    ON client.id_client = ordering.id_client 
 WHERE month(order_date) = 1 
 GROUP 
    BY name;

**Descripton**: (https://i.imgur.com/TrUGOLW.png)

**Example of my query** (there are 6 notes about clients at my db, showed only 4 of 6):

(https://i.imgur.com/ABP6pP0.png)

**MRE stuff**
Client: create table client(id_client int primary key auto_increment, name var char(50), passport_code int, addr varchar(70));
insert into client values(null, 'Penny Anderson', 6485, 'New Orlean');

Ordering: create table ordering(id_order int primary key auto_increment, id_client int, order_date date, foreign key(id_client) references client(id_client));
insert into ordering values(null, 1, date('2020-05-01'));
mysql join where-clause
1个回答
0
投票

试着从客户的表开始进行简单的左连接。

    SELECT client.name
         , client.id_client
         , COUNT(order_date) 
      FROM client 
     LEFT JOIN  ordering  ON client.id_client = ordering.id_client 
       AND  month(ordering.order_date) = 1 
     GROUP  BY client.id_client;

如果连接的条件与左连接表相关,那么在相关的ON子句中添加这个条件,而不是在where子句中添加,否则这个工作就像内部连接一样。

© www.soinside.com 2019 - 2024. All rights reserved.