MYSQL在一列中搜索多个条件

问题描述

table1
-------------------------------
| id | color     | shape      |
|------------------------------
|  1 | green     | triangle   |
|  2 | green     | square     |
|  3 | blue      | rectangle  |
|  4 | white     | sphere     |
|  5 | yellow    | triangle   |
-------------------------------

我想得到一个结果,其中行在一个列中具有多个条件。 这是我的代码

SELECT * FROM table1 WHERE shape = 'triangle' and shape = 'square';

但是,结果的列颜色应具有相同的值。 可能会有以下结果吗?

-------------------------------
| id | color     | shape      |
|------------------------------
|  1 | green     | triangle   |
|  2 | green     | square     |
-------------------------------

解决方法

一个选项使用not exists

select t.*
from mytable t
where 
    shape in ('triangle','square')
    and exists (
        select 1
        from mytable t1
        where 
            t1.shape in ('triangle,'square')
            and t1.color = t.color
            and t1.shape <> t.shape
    )

如果运行的是MySQL 8.0,则还可以使用窗口函数。假设(color,shape)元组中没有重复项:

select id,color,shape
from (
    select t.*,count(*) over(partition by color) cnt
    from mytable t
    where shape in ('triangle','square')
) t
where cnt > 1