如何根据其他两列的不同组合检查第三列的匹配值?

时间:2019-06-14 14:46:17

标签: mysql mysql-workbench

我有一个带有建筑物名称的表,例如A,B,C。这些建筑物名称可以重复。我还有另外一个专栏发言。例如第1层,第2层。同样,每个建筑物可能有多个第1层。第三列显示对象,例如电视,砖块,风扇。 我想检查建筑物与相应楼层的每种组合,例如A楼-1楼,A楼-2楼,如果存在对象“砖”,则必须存在“墙”。

示例数据: 对于每个建筑物和位置,如果存在“ WALL”,“ WINDOW”,“ WINDOW1”或“ WINDOW2”,则其他标志

BUILDING  LOCATION  OBJECT   
A         FLOOR1    WALL
A         FLOOR1    WINDOW  
A         FLOOR2    WALL  
B         FLOOR1    WALL  
C         FLOOR1    WALL  
C         FLOOR1    WINDOW

期望的输出

BUILDING  LOCATION  ACTION  

A         FLOOR2    FLAG
B         FLOOR1    FLAG

我尝试使用GROUP BY,DISTINCT,WHERE EXISTS,但是我似乎无法提出正确的逻辑。

2 个答案:

答案 0 :(得分:0)

嵌套表是您想要的。像

select column_3
from (
  select *
  from table
  where table.column_3="brick"
) as e
join table t on t.id = e.id
where table.column_3="window"

fyi:我建议您以此为起点,但是对于您的确切情况,我想这需要进行修改

答案 1 :(得分:0)

您可以group by building, locationwhere object in ('WALL', 'WINDOW')

select building, location, 'FLAG' action
from tablename
where object in ('WALL', 'WINDOW')
group by building, location
having count(distinct object) < 2

count(distinct object) < 2子句中的条件having返回building, location的组合,其中'WALL''WINDOW'都不存在。
请参见demo
结果:

| building | location | action |
| -------- | -------- | ------ |
| A        | FLOOR2   | FLAG   |
| B        | FLOOR1   | FLAG   |

或不存在:

select t.building, t.location, 'FLAG' action
from tablename t
where object in ('WALL', 'WINDOW')
and not exists (
  select 1 from tablename
  where building = t.building and location = t.location and object <> t.object
)

请参见demo