sql 多條件查詢使用多個條件篩選數據。語法:select column1, column2, … from table_name where condition1 and condition2 and …。示例:查找居住在加州、名稱包含 “john”、客戶 id 大于 100 的客戶。查詢:select customer_name from customers where city = ‘san francisco’ and customer_name like ‘%john%’ an
SQL 多條件查詢
多條件查詢是指在一個 SQL 語句中使用多個條件來篩選數據。
語法:
SELECT column1, column2, ... FROM table_name WHERE condition1 AND condition2 AND ...
登錄后復制
使用示例:
假設有一個名為 “customers” 的表,包含以下列:
customer_id
customer_name
city
state
查詢滿足以下條件的客戶:
居住在加州
名稱包含 “John”
客戶 ID 大于 100
SQL 查詢:
SELECT customer_name FROM customers WHERE city = 'San Francisco' AND customer_name LIKE '%John%' AND customer_id > 100;
登錄后復制
解釋:
WHERE 子句指定了三個條件:
city = ‘San Francisco’:指定城市為 “San Francisco”。
customer_name LIKE ‘%John%’:指定包含 “John” 的客戶名稱(使用通配符 %)。
customer_id > 100:指定客戶 ID 大于 100。
AND 運算符連接了這些條件,表示所有條件必須同時為真才能返回匹配的行。
其他運算符:
除了 AND 運算符之外,還可以使用以下運算符進行多條件查詢:
OR:返回滿足任意條件的行。
NOT:反轉條件。
提示:
使用括號來組合復雜條件。
使用通配符(% 和 _)來匹配部分字符串。
索引表以提高多條件查詢的性能。