簡體   English   中英

MySQL查詢-根據條件選擇

[英]MySQL Query - SELECT based on condition

對於這個看似簡單的問題,我找不到答案。 我需要根據條件執行不同的SELECT語句。

一個簡單的例子:

if <condition>

SELECT id FROM table;

otherwise

SELECT id FROM table WHERE variable=1;

換句話說,我需要根據條件添加一個額外的WHERE子句,但是問題歸結為根據條件是true還是false選擇不同的SELECT子句。

SELECT id FROM table WHERE variable=1 OR <condition>

case語句也可以使用...

SELECT id FROM table
where case when variable is not null then variable else 1 end
=
case when variable is not null then @variable else 1 end

您可能需要在case語句中使用不同的邏輯,但這是說當變量具有值(非null)時,請使用where子句變量= @variable,否則使用1 = 1(不帶任何過濾器)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM