MYSQL 在一列中搜索多个条件

MYSQL search multiple condition in one column

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
    )

如果你是运行MySQL8.0,也可以使用window功能。假设 (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