返回介绍

solution / 0100-0199 / 0183.Customers Who Never Order / README_EN

发布于 2024-06-17 01:04:03 字数 3110 浏览 0 评论 0 收藏 0

183. Customers Who Never Order

中文文档

Description

Table: Customers

+-------------+---------+
| Column Name | Type  |
+-------------+---------+
| id      | int   |
| name    | varchar |
+-------------+---------+
id is the primary key (column with unique values) for this table.
Each row of this table indicates the ID and name of a customer.

 

Table: Orders

+-------------+------+
| Column Name | Type |
+-------------+------+
| id      | int  |
| customerId  | int  |
+-------------+------+
id is the primary key (column with unique values) for this table.
customerId is a foreign key (reference columns) of the ID from the Customers table.
Each row of this table indicates the ID of an order and the ID of the customer who ordered it.

 

Write a solution to find all customers who never order anything.

Return the result table in any order.

The result format is in the following example.

 

Example 1:

Input: 
Customers table:
+----+-------+
| id | name  |
+----+-------+
| 1  | Joe   |
| 2  | Henry |
| 3  | Sam   |
| 4  | Max   |
+----+-------+
Orders table:
+----+------------+
| id | customerId |
+----+------------+
| 1  | 3      |
| 2  | 1      |
+----+------------+
Output: 
+-----------+
| Customers |
+-----------+
| Henry   |
| Max     |
+-----------+

Solutions

Solution 1: NOT IN

List all customer IDs of existing orders, and use NOT IN to find customers who are not in the list.

import pandas as pd


def find_customers(customers: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame:
  # Select the customers whose 'id' is not present in the orders DataFrame's 'customerId' column.
  df = customers[~customers["id"].isin(orders["customerId"])]

  # Build a DataFrame that only contains the 'name' column and rename it as 'Customers'.
  df = df[["name"]].rename(columns={"name": "Customers"})

  return df
# Write your MySQL query statement below
SELECT name AS Customers
FROM Customers
WHERE
  id NOT IN (
    SELECT customerId
    FROM Orders
  );

Solution 2: LEFT JOIN

Use LEFT JOIN to join the tables and return the data where CustomerId is NULL.

# Write your MySQL query statement below
SELECT name AS Customers
FROM
  Customers AS c
  LEFT JOIN Orders AS o ON c.id = o.customerId
WHERE o.id IS NULL;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文