我有一个包含2列的mysql表。
+---------+-----------+
| Barcode | StationID |
+---------+-----------+
| 89411 | 1 |
| 89411 | 2 |
| 89411 | 3 |
| 89412 | 1 |
| 89413 | 1 |
+---------+-----------+
我想从“条形码”列中选择所有StationID = 1且不具有不同于1的StationID的值。
如图所示,条形码89411出现了3次,但StationID不同,应该从结果中排除。
您能帮我查询吗?
答案 0 :(得分:1)
另一种方法是使用EXISTS
查询:
SELECT t1.*
FROM yourTable t1
WHERE
t1.StationID = 1 AND
NOT EXISTS (SELECT 1 FROM yourTable t2
WHERE t1.Barcode = t2.Barcode AND t2.StationID <> 1);
答案 1 :(得分:0)
尝试一下:https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=641d334c5f9e57bbdde07e4f24365f88
select barcode from tablename
group by barcode
having sum(case when sanctionid=1 then 0 else 1 end)=0
输出:
barcode
89412
89413
答案 2 :(得分:0)
使用聚合函数GROUP_CONCAT,并使用HAVING
子句过滤掉只有一个StationID
即'1'
的那些条形码:
SELECT barcode, GROUP_CONCAT(DISTINCT StationID) AS stations
FROM table_name
GROUP BY barcode
HAVING stations = '1';