2017-03-27 76 views
0

我有一個像選擇是否cl.t_sc_1 = 1或cl.t_sc_2 = 1或cl.t_sc_3 = 1分AND列1 = 10

SELECT DISTINCT SQL_CALC_FOUND_ROWS cl.id AS id, 
cl.column1 AS column1, 
cl.column2 AS column2, 
cl.column3 AS column3, 
cl.t_sc_1 AS t_sc_1, 
cl.t_sc_2 AS t_sc_2, 
cl.t_sc_3 AS t_sc_3 
FROM classifieds AS cl 
WHERE (cl.t_sc_1 = 1 OR cl.t_sc_2 = 1 OR cl.t_sc_3 = 1) 
AND column1 = 10 AND column2=10 AND column3=10 
ORDER BY cl.id ASC 

而且我想要得到結果的查詢是否(t_sc_1 = 1或t_sc_2 = 1 OR t_sc_3 = 1)OR the_three_columns = 1 AND column1 = 10 etc,...我得到resluts,其中t_sc_1 = 1,t_sc_2 = 1,t_sc_3 = 1,column1 = 10等。 因此,只有t_sc_1 = 1的行或者只有column3 = 1的行纔會顯示在結果中。

真正的查詢是動態的,有時'OR'部分包含兩個cl.t_sc_1 = 1(例如(cl.t_sc_1 = 1或cl.t_sc_2 = 1))有時包含三個例子。

我知道子句是否不存在,但有沒有辦法實現這一點?

感謝您的幫助

+0

提供您的CODE –

回答

1

您當前的查詢省略了一些,你口頭上向我們描述的邏輯。試試這個:

select * 
from yourTable 
where (column1 = 1 or column2 = 1 or column3 = 1) or 
     ((column1 = 1 and column2 = 1 and column3 = 1) and column4 = 10) 
order by id asc 

有了這個邏輯,一個只有column2 = 1的記錄將被返回。

+0

我這樣做是這樣的:從yourTable '選擇* 其中(列1 = 1或欄3 = 1)或 ((column1 = 1和column3 = 1)和column4 = 10) order by id asc'但是隻有column1 = 1的結果或只有column3 = 1的結果沒有顯示 – Cactux

2

我們叫

column1 = 1 as a 
column2 = 1 as b 
column3 = 1 as c 
column4 = 10 as d 

你說你想要的是:

(a + b + c) + (a.b.c.d) 
= a + b + c + a.b.c.d 

其中,使用布爾代數,等效於:

a + b + c.(1 + a.b.d) 
= a + b + c.1 
= a + b + c 

含義是:

where (
    column1 = 1 
    or column2 = 1 
    or column3 = 1 
    ) 
or (
    column1 = 1 
    and column2 = 1 
    and column3 = 1 
    and column4 = 10 
    ) 

等同於:

where column1 = 1 
    or column2 = 1 
    or column3 = 1 

或者:

where 1 in (column1, column2, column3); 
+0

你能幫我嗎? http://stackoverflow.com/qu estions/43052465/how-do-i-create-procedure-which-do-similar-job-of-php-function-optimizatio) – user3637224

+0

對我不起作用。 – Cactux

+0

@Cactux - *不工作*不是非常翔實。請編輯您的問題,並提供樣本數據,期望輸出和輸出背後的邏輯。 – GurV