MySQL选择A行和B行(如果存在A行)

时间:2019-05-07 17:59:47

标签: mysql amazon-rds

我有一个包含两列,不同类型ID的表。如果第二列(widget_id)中有特定的ID(2),则在两种情况下,我都希望有所有第一列ID的列表:

  1. 如果同一第一列ID的widget_id也为1,则
  2. 如果没有相同的第一列ID的widget_id为1。

当前,我有一个查询,该查询可捕获widget_id为1或2的所有行。如何集中精力处理我需要的内容?

我当前的查询:

gst-launch-1.0 -e \
videomixer name=mix \
    sink_0::xpos=0   sink_0::ypos=0  sink_0::alpha=0\
    sink_1::xpos=640   sink_1::ypos=0 \
rtspsrc location=rtsp://192.168.9.20:554/axis-media/media.amp user-id=username user-pw=password latency=150 \
! decodebin max-size-time=30000000000 \
! videoconvert ! videoscale \
! video/x-raw,width=640,height=480 \
! mix.sink_1 \
rtspsrc location=rtsp://192.168.9.24:554/axis-media/media.amp user-id=username user-pw=password latency=150 \
! decodebin max-size-time=30000000000 \
! videoconvert ! videoscale \
! video/x-raw,width=640,height=480 \
! mix.sink_2 \
mix. ! queue ! videoconvert ! autovideosink

输出:

SELECT *
FROM db.table
WHERE (widget_id = 1 OR widget_id = 2)
ORDER BY gadget_id;

我正在寻找的输出:

#1和#2两者:

+----------+----------+
|gadget_id |widget_id |
+----------+----------+
|100       |1         |
|101       |1         |
|101       |2         |
|102       |1         |
|103       |2         |
|104       |1         |
|104       |2         |
|105       |2         |
+----------+----------+

仅#2:

+----------+----------+
|gadget_id |widget_id |
+----------+----------+
|101       |1         |
|101       |2         |
|104       |1         |
|104       |2         |
+----------+----------+

1 个答案:

答案 0 :(得分:1)

在两种情况下,您都需要group by gadget_id
对于第一种情况,条件是1和2必须同时存在:

select * from tablename 
where gadget_id in (
  select gadget_id
  from tablename
  where widget_id in (1, 2)
  group by gadget_id
  having count(distinct widget_id) = 2
) 

对于第二种情况,条件是1不能存在:

select * from tablename 
where gadget_id in (
  select gadget_id
  from tablename
  where widget_id in (1, 2)
  group by gadget_id
  having sum(widget_id = 1) = 0 
)

如果widget_id列中仅有1和2,则可以省略条件:

where widget_id in (1, 2)
在两个查询中都是


请参见demo
结果:

查询#1

| gadget_id | widget_id |
| --------- | --------- |
| 101       | 1         |
| 101       | 2         |
| 104       | 1         |
| 104       | 2         |

查询#2

| gadget_id | widget_id |
| --------- | --------- |
| 103       | 2         |
| 105       | 2         |