MySQL ORDER BY结果从sub select as INTEGER

时间:2015-08-11 16:08:28

标签: mysql

我的ORDER BY(ORDER BY count_wall)按字符串排序,但我将按整数排序:

(SELECT COUNT(wc.id) FROM weighting_contra wc WHERE wc.entry_contra_id in (1,2,3,4)) as count_wc,
(SELECT COUNT(wp.id) FROM weighting_pro wp WHERE wp.entry_pro_id in (1,2,3,4)) as count_wp,
(SELECT IFNULL(count_wc,0) + IFNULL(count_wp,0)) as count_wall

我在ORDER BY子句中测试了count_wall * 1和ABS(count_wall)或ABS()...没有任何帮助,它按字符串排序。 我无法理解这一点,因为count_wall绝对是一个整数。 也许有人可以帮助我。

我找到了一些:ORDER BY与CASE不工作......这里完整,不工作,代码:

CREATE DEFINER=`root`@`localhost` PROCEDURE `proc_test_order_by`(p_order_by VARCHAR(20))
BEGIN
select
t.id as topic_id, t.title as topic_title, t.alias as topic_alias, t.time_create, t.is_public,
(SELECT COUNT(ec.id) FROM entry_contra ec WHERE ec.topic_id = t.id) as count_ec,
(SELECT COUNT(ep.id) FROM entry_pro ep WHERE ep.topic_id = t.id) as count_ep,
(SELECT IFNULL(count_ec,0) + IFNULL(count_ep,0)) as count_eall,

(SELECT COUNT(wc.id) FROM weighting_contra wc WHERE wc.entry_contra_id in (SELECT ec.id FROM entry_contra ec WHERE ec.topic_id = t.id)) as count_wc,
(SELECT COUNT(wp.id) FROM weighting_pro wp WHERE wp.entry_pro_id in (SELECT ep.id FROM entry_pro ep WHERE ep.topic_id = t.id)) as count_wp,
(SELECT IFNULL(count_wc,0) + IFNULL(count_wp,0)) as count_wall
from topic t
WHERE t.is_public = 1
GROUP BY t.id
ORDER BY 
    CASE p_order_by
    WHEN 'topic_alias' THEN topic_alias 
    WHEN 'time_create' THEN time_create
    WHEN 'count_ec' THEN count_eall
    WHEN 'count_ep' THEN count_eall
    WHEN 'count_wc' THEN count_wall
    WHEN 'count_wp' THEN count_wall
    ELSE time_create
    END
DESC;
END

现在有效的代码:

select
t.id, t.title,
(SELECT COUNT(ec.id) FROM entry_contra ec WHERE ec.topic_id = t.id) as count_ec,
(SELECT COUNT(ep.id) FROM entry_pro ep WHERE ep.topic_id = t.id) as count_ep,
(SELECT IFNULL(count_ec,0) + IFNULL(count_ep,0)) as count_eall,

(SELECT COUNT(wc.id) FROM weighting_contra wc WHERE wc.entry_contra_id in (SELECT ec.id FROM entry_contra ec WHERE ec.topic_id = t.id)) as count_wc,
(SELECT COUNT(wp.id) FROM weighting_pro wp WHERE wp.entry_pro_id in (SELECT ep.id FROM entry_pro ep WHERE ep.topic_id = t.id)) as count_wp,
(SELECT IFNULL(count_wc,0) + IFNULL(count_wp,0)) as count_wall
from topic t
WHERE t.is_public = 1
GROUP BY t.id
ORDER BY count_wall
DESC;

......有人可以解释一下吗?

0 个答案:

没有答案