MySQL基于其他SELECT订购SELECT

时间:2014-06-21 05:51:21

标签: mysql

我有两个选择:

SELECT ent_user, ent_video_type, count(*) AS total 
FROM entry WHERE ent_user='1' 
GROUP BY ent_video_tipo 
ORDER BY total DESC

ent_user|ent_video_type|total
    1   |       1      |  3
    1   |       3      |  2
    1   |       4      |  1

我还有其他选择:

SELECT * FROM meta

met_id|met_name|user_id|met_type
   10 |  bla   |   2   |    1
   11 | blabla |   4   |    2
   12 |  foo   |   1   |    3
   13 | blafoo |   3   |    4
   14 | foofoo |   5   |    4

如何订购最后一个选择,如下所示:

met_id|met_name|user_id|met_type
   10 |  bla   |   2   |    1
   12 |  foo   |   1   |    3
   13 | blafoo |   3   |    4
   14 | foofoo |   5   |    4
   11 | blabla |   4   |    2

我想按met_type排序最后一次选择,具体取决于第一个选择。我想ent_video_type = met_type,因此我可以按met_type订购最后一次选择。

我该怎么做?

我想按照met_type列的顺序订购ent_video_type列。

3 个答案:

答案 0 :(得分:1)

实际上,在第一个“选择”字段中,不允许使用“ent_user”。它既没有在字段中提及也没有在集合函数中提及。所以我想知道你是如何得到答案的。

无论如何,基于相同的代码,我已将“ent_user”添加到“group by”子句中,并编写了此解决方案:

我添加了extraField只是为了订购。

Select meta.*, 1 as extraField 
    From meta
        inner join (
            SELECT ent_user, ent_video_type, count(*) AS total 
                FROM entry WHERE ent_user='1' 
                GROUP BY ent_user, ent_video_tipe
            ) as t1 on meta.met_type = t1.ent_video_type
union all
Select *, 2 
    From meta
    Where met_type not in (
            SELECT distinct ent_video_type
                FROM entry WHERE ent_user='1' 
        ) 
Order by extraField, met_type

如果您不希望显示extraField,则可以使用此选项:

Select met_id, met_name, user_id, met_type
    From (
        Select meta.*, 1 as extraField 
            From meta
                inner join (
                    SELECT ent_user, ent_video_type, count(*) AS total 
                        FROM entry WHERE ent_user='1' 
                        GROUP BY ent_user, ent_video_tipe
                    ) as t1 on meta.met_type = t1.ent_video_type
        union all
        Select *, 2 
            From meta
            Where met_type not in (
                    SELECT distinct ent_video_type
                        FROM entry WHERE ent_user='1' 
                ) 
        ) as t1
    Order by extraField, met_type

答案 1 :(得分:0)

SELECT met_id, met_name, user_id, met_type, ent_user, ent_video_type, count(*) AS total  
FROM meta

LEFT JOIN entry ON ent_video_type = met_type

WHERE ent_user='1' 

GROUP BY ent_video_type 

ORDER BY total DESC

答案 2 :(得分:0)

SELECT E.ent_user, E.ent_video_type, count(*) AS total 
FROM entry E
left outer join meta M on E.ent_video_type=M.met_type
WHERE E.ent_user='1' 
GROUP BY E.ent_video_type 
ORDER By total DESC