MySQL select,between,AND,OR子句和查询问题

时间:2010-06-22 09:36:50

标签: sql mysql

我有一个名为item的表,其中包含两个属性(codename)。
现在我想以下列方式对它们进行分组:

group a: code between (5300 and 5310),(7100,7200),(8210,8290)
group b: code not between (5300 and 5310),(7100,7200),(8210,8290)

我怎样才能使用MySQL查询呢?

2 个答案:

答案 0 :(得分:4)

'group'是什么意思?

如果您想使用GROUP BY,您可以这样做:

SELECT
    CASE
        WHEN
            code BETWEEN 5300 AND 5310 OR
            code BETWEEN 7100 AND 7200 OR
            code BETWEEN 8210 AND 8290
        THEN 'Group A'
        ELSE 'Group B'
    END AS grp,
    COUNT(*) AS cnt
FROM your_table
GROUP BY grp

也许您只想订购BY?

SELECT
    CASE
        WHEN
            code BETWEEN 5300 AND 5310 OR
            code BETWEEN 7100 AND 7200 OR
            code BETWEEN 8210 AND 8290
        THEN 'Group A'
        ELSE 'Group B'
    END AS grp,
    *
FROM your_table
ORDER BY grp

另请注意,BETWEEN包含两个可能与您无关的端点。

答案 1 :(得分:2)

组a:

SELECT * FROM theTable 
WHERE 
  code >= 5300 AND code <= 5310 OR 
  code >= 7100 AND code <= 7200 OR  
  code >= 8210 AND code <= 8290

组b:

SELECT * FROM theTable 
WHERE 
  code < 5300 OR
  code > 5310 AND code < 7100 OR
  code > 7200 AND code < 8210 OR
  code > 8290

一切

SELECT *, 'A' FROM theTable 
WHERE 
  code >= 5300 AND code <= 5310 OR 
  code >= 7100 AND code <= 7200 OR  
  code >= 8210 AND code <= 8290
UNION
SELECT *, 'B' FROM theTable 
WHERE 
  code < 5300 OR
  code > 5310 AND code < 7100 OR
  code > 7200 AND code < 8210 OR
  code > 8290