2023-11-28|閱讀時間 ‧ 約 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.