MYSQL返回空结果集?

时间:2012-06-22 15:09:31

标签: mysql

我有一个具有以下结构的表:

CREATE TABLE IF NOT EXISTS `user_settings` (
  `user_ID` smallint(6) unsigned NOT NULL,
  `item` varchar(50) NOT NULL,
  `value` text,
  `app_ID` tinyint(4) NOT NULL DEFAULT '0',
  KEY `user_ID` (`user_ID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

# With these data

INSERT INTO `user_settings` (`user_ID`, `item`, `value`, `app_ID`) VALUES
(3, 'statusTrainer_ID', '0', 0),
(3, 'enabledApp', '1', 0),
(3, 'enabled_office_ID', '1', 1),
(3, 'enabled_office_ID', '2', 1),
(4, 'statusTrainer_ID', '1', 0),
(1, 'enabledApp', '1', 0),
(1, 'salesCode_ID_add', '1', 1),
(1, 'salesCode_ID_add', '2', 1),
(1, 'salesCode_ID_add', '3', 1),
(1, 'salesCode_ID_add', '20', 1),
(1, 'salesCode_ID_process', '2', 1),
(1, 'salesCode_ID_process', '3', 1),
(1, 'salesCode_ID_process', '20', 1);

我想运行此查询进行数据过滤

SELECT `user_ID`
FROM (`user_settings`)
WHERE (
`item` =  'enabledApp'
 AND 
`value` IN ('1') 
)
 AND 
(
`item` =  'statusTrainer_ID'
 AND 
`value` IN ('0') 
)

我期待结果为'3'但是MYSQL返回一个空集。为什么??谢谢你的回答。

已更新

我通过子查询解决了它

SELECT distinct `user_ID`
FROM (`user_settings`)
WHERE user_ID IN(
SELECT `user_ID`
FROM (`user_settings`)
WHERE (
item =  'enabledApp'
 AND 
value IN (1) 
))

AND user_ID IN(SELECT `user_ID`
FROM (`user_settings`)
WHERE (
item =  'statusTrainer_ID'
 AND 
value IN (0) 
))

Demo

但它有点复杂......是否有一些更清洁的解决方案????

1 个答案:

答案 0 :(得分:1)

你需要一个或:

SELECT `user_ID`
FROM (`user_settings`)
WHERE ( `item` =  'enabledApp'  AND  `value` IN ('1')  )  OR
      ( `item` =  'statusTrainer_ID'  AND  `value` IN ('0')  ) 

它返回空集,因为item不能同时是“enabledApp”和“statusTrainer_ID”。

哦,你正试图让用户ID同时拥有。这样做:

SELECT `user_ID`
FROM `user_settings`
GROUP BY `user_ID`
HAVING max(case when `item` =  'enabledApp'  AND  `value` IN ('1') then 1 else 0 end) = 1 and
       max(case when  `item` =  'statusTrainer_ID'  AND  `value` IN ('0') then 1 else 0 end) = 1

Demo