1

请我有以下表格

Field
+----+--------+----------+---------------------+
| id | name   | Type     | date                |
+----+--------+----------+---------------------+
|  1 |  price | int      | 2009-09-02 00:07:07 |
|  2 |  width | float    | 2009-09-02 00:07:08 |
|  3 |  height| float    | 2009-09-02 00:07:30 |
+----+--------+--------------------------------+


Post
+----+--------+---------------------------------+
| id |title   | Body                            |
+----+--------+---------------------------------+
|  1 |  test  | Bla bla bla                     |
|  2 | Hello  | Bla bla bla                     |
|  3 | Its me | Bla bla bla                     | 
+----+--------+---------------------------------+


Post_Annex
+----+--------+----------+---------------------+
| id | IdPost | IdField  | Value               |
+----+--------+----------+---------------------+
|  1 |  1     | 1        | 50                  |
|  2 |  1     | 2        | 21                  |
|  3 |  1     | 3        | 3                   |
|  4 |  2     | 1        | 10                  |
|  5 |  2     | 2        | 2                   |
|  6 |  2     | 3        | 150                 |
|  7 |  3     | 1        | 1                   |
|  8 |  3     | 2        | 25                  |
|  9 |  3     | 3        | 15                  |
+----+--------+--------------------------------+

我希望从PostPost_Annex表中选择数据,按 Post 表的 Id 对它们进行分组并按价格排序(这意味着当 Post_Annex 表的 IdField 等于 1 时)。所以这是我的查询:

SELECT p.title
    FROM Post p
    LEFT JOIN Post_Annex pa
       ON p.id = pa.IdPost

    GROUP BY p.id

    ORDER BY case when pa.IdField = 1 then 0 else 1, pa.Value DESC

这给了我这个顺序的结果:its Me | Hello | test

这可以。但即使我尝试按宽度(IdField = 2)或高度(IdField = 3)排序,它也给了我相同的结果。

请掌握任何想法来帮助我解决这个问题?提前致谢。

4

2 回答 2

3

我只想修改 join 子句,以指定要排序的字段:

SELECT p.title
FROM Post p
     LEFT JOIN Post_Annex pa
     ON p.id = pa.IdPost
        AND pa.idfield=1
ORDER BY pa.Value DESC

然后您不必按 p.id 分组。

您的查询并不总是有效,因为您正在分组,p.id但您正在选择(和排序)其他非聚合列,并且这些列的值可以是undeteminate

于 2013-01-21T23:27:39.240 回答
0

在一个简单的 SQL 中,避免 group by 和 case when 的:

SELECT p.title
FROM Post p, Post_Annex pa
WHERE p.id = pa.IdPost
AND pa.IdField = 1
ORDER BY pa.Value DESC

你可以这样做。

于 2013-01-21T23:43:19.453 回答