MYSQL中WHERE子句的大小写

MYSQL中WHERE子句的大小写,mysql,case,where,clause,Mysql,Case,Where,Clause,问题正如标题所说的那样简单,但这里有一个逻辑。 这是我的密码 CREATE TABLE `inf_brand_images` ( `id` bigint(99) NOT NULL AUTO_INCREMENT, `brand` varchar(255) NOT NULL, `thumb` text NOT NULL, `is_active` int(2) NOT NULL DEFAULT '1', `cmp_brand` varchar(1024) NOT NULL, PRIMARY KEY (

问题正如标题所说的那样简单,但这里有一个逻辑。 这是我的密码

CREATE TABLE `inf_brand_images` (
`id` bigint(99) NOT NULL AUTO_INCREMENT,
`brand` varchar(255) NOT NULL,
`thumb` text NOT NULL,
`is_active` int(2) NOT NULL DEFAULT '1',
`cmp_brand` varchar(1024) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6458 DEFAULT CHARSET=latin1
这是这个表中的数据

ID | brand  | thumb  |is_active| cmp_brand
1  | NIKE   | a.png  | 1       | 
2  | DUNHILL| b.png  | 1       |
3  | NIKE   | c.png  | 1       | 123_NIKE
4  | NIKE   | d.png  | 1       | 789_NIKE
在我的例子中,cmp_品牌的前缀是他们的一些ID,如123_和789_。 现在,如果我搜索NIKE,那么我有两个参数,一个是NIKE,另一个是id_NIKE。其中id可能是123或456或任何其他。因此,对于NIKE search,我有两个参数,一个是brand=NIKE,另一个是cmp_brand=123_NIKE(我会自动使用品牌名称取消id)

我想要的是

IF cmp_brand is '' then compare with brand ELSE compare brand AND cmp_brand.
这是我试过的,都不起作用

SELECT thumb 
FROM inf_brand_images 
where is_active=1  AND 
CASE WHEN cmp_brand = '' THEN brand='NIKE' 
ELSE cmp_brand='123_NIKE' END

 SELECT thumb 
 FROM inf_brand_images 
 where is_active=1 AND 
((cmp_brand = '' AND brand='NIKE') OR (cmp_brand='123_NIKE'))

您的第二次尝试是正确的,使用逻辑
和/或
分组而不是
案例
,但是如果您希望行匹配
cmp\u品牌
而不是带有空
cmp\u品牌
的行,并且只希望返回一个结果,按照
组织您的
订单,首先对非空的
cmp_品牌
进行排序,并将总体结果限制为1

SELECT thumb 
FROM inf_brand_images 
WHERE
  is_active=1 AND 
  ((cmp_brand = '' AND brand='NIKE') OR (cmp_brand='123_NIKE'))
/* non-empty cmp_brand will sort first */
ORDER BY cmp_brand <> '' DESC
/* and the end result is limited only to the first sorted row
   which will be the cmp_brand if matched, or the brand otherwise */
LIMIT 1
  • 以下是123_NIKE比赛的示例:
  • 以及124_NIKE不匹配的示例:

我希望您的第二个查询能够正常工作。这是正确的方法(逻辑分组和/或,不是案例),您是否期望此查询的结果与
ID=1,ID=3
不同?根据我的阅读,这是预期结果。第二次查询给我记录编号1,3,但我只需要3。意思是我只需要c.pngOk,所以你想选择
cmp_品牌
匹配而不是
品牌
匹配?小心!有时rdms系统将零长度字符串表示为空值。在这种情况下,
column='
将不为真,但
column为空
将为真。@Micheal:这很好,但如果我想获得更多记录,它将给我错误的数据…例如,如果我有另一条记录,“(5,'NIKE','e.png',1,'123nike')”如果cmp_品牌为“”,则不需要显示/检查品牌。我的问题很清楚,如果cmp_品牌匹配,则不需要比较品牌。如果cmp_品牌不匹配,则需要比较品牌。@user3244721好的,如果需要返回更多行,则比较复杂,但我找到了一种工作方法。
SELECT DISTINCT
  CASE WHEN cbcb IS NOT NULL THEN cbthumb ELSE bthumb END AS thumb
FROM (
  /* Return thumbs from both sides of the join */
  SELECT 
    b.thumb AS bthumb,
    b.cmp_brand AS bcb,
    cb.thumb AS cbthumb,
    cb.cmp_brand AS cbcb
  FROM
    inf_brand_images b
    /* join the table against itself with the matching cmp_brand in the join condition */
    LEFT JOIN inf_brand_images cb
      ON b.brand = cb.brand
      AND cb.cmp_brand = '123_NIKE'
  WHERE 
    /* The WHERE clause looks for empty cmp_brand on the left side of the join */
    b.brand = 'NIKE' AND b.cmp_brand = ''
) thumbs