SQL:如何在Sql中使用条件AND和OR

时间:2013-10-28 06:00:19

标签: mysql sql relational-database

我的表格中包含以下值

docid dcname doctitle 
1      **aa   **aaa01-01 
2      aa**   aafddg-02**
3      a**a   asds***90-05
4      abcd   abcd-06.

现在在这个表中我想过滤以**

开头和结尾的“Doctitles”值

我的结果应该是

dcid docname doctitle
3    a**a    asds***90-05
4    abcd    abcd-06

我正在使用以下查询,但获得的结果只是Doctitles,其中**位于中间

SELECT *
  FROM table1
 WHERE     doctitle NOT LIKE '**%'
       AND doctitle NOT LIKE '%**'
       AND doctitle LIKE '%**%'

这只给出了我的结果 dcid docname doctitle 3 a * a asds ** 90-05

需要帮助。

6 个答案:

答案 0 :(得分:0)

在没有and doctitle like '%**%'的情况下尝试 您的查询应该是select * from table1 where doctitle not like '**%' and doctitle not like '%**'

另一种解决方案:

SELECT * FROM table1 WHERE LEFT(doctitle,2) != '**' AND RIGHT(doctitle,2) != '**'

答案 1 :(得分:0)

尝试以下选项

select * from table1 where doctitle like '**%' and doctitle like '%**'

select * from table1 where doctitle like '**%'
UNION
select * from table1 where doctitle like '%**'

有关详细信息,请参阅this

答案 2 :(得分:0)

我尝试了它并且它有效 -

select * from 
(
select 
1    docid ,  '**aa' dcname  ,  '**aaa01-01' doctitle 
from dual
union all  
select 
2,      'aa**',   'aafddg-02**'
from dual
union all
select 
3 ,     'a**a' ,  'asds***90-05'
from dual
union all
select 
4  ,    'abcd'  , 'abcd-06.'
from dual
)
where doctitle not like '**%' and doctitle not like '%**'  

答案 3 :(得分:0)

假设您的意思是希望doctitle**开头或结尾,您只需要省略最后一个条件:

SELECT *
FROM   table1
WHERE  doctitle NOT LIKE '**%'
  AND  doctitle NOT LIKE '%**'

答案 4 :(得分:0)

试试这个..

SELECT  *
FROM    table1
WHERE   doctitle LIKE '%**%'
AND     docid  NOT IN (SELECT docid  FROM tabel1 WHERE doctitle NOT LIKE '**%' )
AND     docid  NOT IN (SELECT docid  FROM tabel1 WHERE doctitle NOT LIKE '%**' )

答案 5 :(得分:0)

SELECT *   FROM table1   doct不是'%'   或者doctitle不喜欢'%'