Mysql从一个表中选择

时间:2018-04-20 18:04:17

标签: mysql

我的表结构是

id;product_id;sell_type;sell_state

sell_type: BUY, SELL

sell_state: OPEN, FILLED, CANCELED

如何仅针对每两项操作选择product_idBUY & SELL中的sell_typeFILLED中的sell_state

CREATE TABLE `orderlist` (
  `id` int(10) UNSIGNED NOT NULL,
  `product_id` int(11) NOT NULL,
  `sell_type` enum('BUY','SELL') DEFAULT NULL,
  `sell_state` enum('OPEN','FILLED','CANCELED') DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


INSERT INTO `orderlist` (`id`, `product_id`, `sell_type`, `sell_state`) VALUES
(7, 1, 'BUY', 'FILLED'),
(8, 1, 'SELL', 'FILLED'),
(9, 2, 'BUY', 'FILLED'),
(10, 3, 'SELL', 'FILLED');

3 个答案:

答案 0 :(得分:2)

你可以使用group by和count(distinct sell_state)= 2

select product_id 
from orderlist  
where sell_state ='FILLED'
and sell_type in ('BUY', 'SELL')
group by product_id 
having count(distinct sell_type) = 2

http://sqlfiddle.com/#!9/c41301/2

答案 1 :(得分:1)

尝试此选择查询

SELECT t1.* 
FROM temp t1
INNER JOIN temp t2
ON t1.product_id = t2.product_id AND FIND_IN_SET('FILLED',t1.sell_state) > 0
WHERE FIND_IN_SET('BUY',t1.sell_type) > 0 AND
CONCAT(",", t2.sell_type, ",") REGEXP ",(BUY|SELL),"
GROUP BY t1.product_id

演示:http://sqlfiddle.com/#!9/7fcd9/64

答案 2 :(得分:1)

试试这个

SELECT product_id
FROM orderlist
WHERE sell_state = 'FILLED' AND sell_type IN ('BUY','SELL')
GROUP BY product_id
HAVING COUNT(product_id) > 2

演示:http://sqlfiddle.com/#!9/464959/2