浓缩多个OR条件

时间:2019-07-20 06:54:52

标签: mysql sql

我必须从一个表中删除多个ID,不幸的是,“ I” ID分散在整个列中。

有什么办法可以压缩这种类型的查询?

DELETE FROM table 
WHERE 
  I1 = 1 OR I2 = 1 OR I3 = 1 OR I4 = 1 OR I5 = 1 OR 
  I6 = 1 OR I7 = 1 OR R1 = 1 OR R2 = 1 OR R3 = 1;

表格:

DROP TABLE IF EXISTS `recipes`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `recipes` (
  `ID` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
  `I1` smallint(5) unsigned NOT NULL,
  `I2` smallint(5) unsigned NOT NULL,
  `I3` smallint(5) unsigned NOT NULL,
  `I4` smallint(5) unsigned NOT NULL,
  `I5` smallint(5) unsigned NOT NULL,
  `I6` smallint(5) unsigned NOT NULL,
  `I7` smallint(5) unsigned NOT NULL,
  `I8` smallint(5) unsigned NOT NULL,
  `R1` smallint(5) unsigned NOT NULL,
  `R2` smallint(5) unsigned NOT NULL,
  `R3` smallint(5) unsigned NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=MyISAM AUTO_INCREMENT=3500 DEFAULT CHARSET=utf8 AVG_ROW_LENGTH=79;
/*!40101 SET character_set_client = @saved_cs_client */;

2 个答案:

答案 0 :(得分:2)

在条件值匹配时尝试以下查询

DELETE FROM table WHERE 1 in (I1,I2,I3,I4,I5,I6,I7,R1,R2,R3);

答案 1 :(得分:0)

您可以CONCAT在其中可以包含id的所有列,并查看结果字符串中是否包含序列“ comma-id-comma”,如下所示:

SELECT * FROM recipes WHERE CONCAT(',' , I1, I2, I3, I4, I5, I6, I7, I8, R1, R2, R3, ',') LIKE '%,1,%'

请注意concat开头和结尾的逗号,这是正确检查I1和R3列所必需的。