更新於 2024/11/27閱讀時間約 4 分鐘

SQL基礎查詢語法 可回收和低脂產品 Leetcode #1757

題目會給我們一張Products資料表,裡面分別有product_id、low_fats、recyclable等欄位,其中product_id 是主鍵Primary Key。

要求我們列出所有的可回收 且 低脂產品的product_id,順序不拘。

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| product_id | int |
| low_fats | enum |
| recyclable | enum |
+-------------+---------+
product_id is the primary key (column with unique values) for this table.
low_fats is an ENUM (category) of type ('Y', 'N') where 'Y' means this product is low fat and 'N' means it is not.
recyclable is an ENUM (category) of types ('Y', 'N') where 'Y' means this product is recyclable and 'N' means it is not.


詳細的題目可在這裡看到


測試範例

Example 1:

Input: 
Products table:
+-------------+----------+------------+
| product_id | low_fats | recyclable |
+-------------+----------+------------+
| 0 | Y | N |
| 1 | Y | Y |
| 2 | N | Y |
| 3 | Y | Y |
| 4 | N | N |
+-------------+----------+------------+
Output:
+-------------+
| product_id |
+-------------+
| 1 |
| 3 |
+-------------+
Explanation: Only products 1 and 3 are both low fat and recyclable.

約束條件

列出所有可回收 且 低脂產品的product_id,順序不拘。


演算法

入門題,複習基礎的SELECT ...欄位 FROM ...表格 WHERE ...條件 SQL語法

依序填入即可

如果是第一次接觸SQL的同學,請到這邊學習基本的SQL 語法


程式碼

SELECT product_id
FROM Products
WHERE low_fats='Y' AND recyclable = 'Y';

關鍵知識點

掌握基本的SELECT ...欄位 FROM ...表格 WHERE ...條件 SQL語法即可


Reference:

[1] MySQL by SELECT...FROM...WHERE... - Recyclable and Low Fat Products - LeetCode

分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.