1

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

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) 
))

演示

但这有点复杂……有更清洁的解决方案吗????

4

1 回答 1

1

你需要一个或:

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

它返回空集,因为项目不能同时是“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

演示

于 2012-06-22T15:55:10.130 回答