按字符长度排序,但不希望过滤

时间:2016-04-20 18:23:08

标签: mysql sql filter

想要评论评论长度< = 250和> = 50

所有短期或长期评论都应该结束......目前我必须过滤它们......但这不是我想要的

当前查询

select
c.id,
c.name,
DATE_FORMAT(c.created,'%d %b %Y') as date_new,
r.ratings,
c.comments,
ROUND((r.ratings_sum / r.ratings_qty),1) as total_rating
from
commentsAS c , rating AS r , id_script i
where
c.pid = i.sub_cat_id
AND i.cat_id = 118
AND r.reviewid = c.id
AND c.published = '1'
AND LENGTH(c.comments) <= 250
AND LENGTH(c.comments) >= 50
ORDER BY c.created DESC

我不想用下面的

过滤它们
AND LENGTH(c.comments) <= 250
AND LENGTH(c.comments) >= 50

3 个答案:

答案 0 :(得分:3)

ORDER BY
    CASE
        WHEN LENGTH(C.comments) > 250 OR LENGTH(C.comments) < 50 THEN 1
        ELSE 0
    END

答案 1 :(得分:2)

在MySQL中,您只需使用布尔表达式即可完成此操作:

order by ( length(c.comments) < 50 or length(c.comments) > 250) desc

MySQL将数字上下文中的布尔值视为整数,true为1。

另一种配方甚至更短:

order by (length(c.comments) between 50 and 249)

答案 2 :(得分:0)

如果您使用新版本的MariaDB,则可以使用虚拟persitent列。如果你插入或更改日期,他们会计算直接新的feld。您还可以在其上使用索引或复合索引。

更改表格

ALTER TABLE comments
ADD COLUMN l INT AS (LENGTH(`comments`)) PERSISTENT,
ADD KEY  (`comments`);

<强>查询

SELECT
  c.id, c.name,
  DATE_FORMAT(c.created,'%d %b %Y') as date_new,
  r.ratings, c.comments,
  ROUND((r.ratings_sum / r.ratings_qty),1) as total_rating
  FROM commentsAS c , rating AS r , id_script i
where
  c.pid = i.sub_cat_id
  AND i.cat_id = 118
  AND r.reviewid = c.id
  AND c.published = '1'
  AND c.l between 50 AND 250
  ORDER BY c.created DESC;