[英]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
)
如果你運行的是MySQL 8.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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.