1

我有两个看起来像这样的表:

表:项目

id | itemId
---|------
0  | 1
1  | 2
2  | 3

表:item_specs

id | itemId | key          | values
---|--------|---------------
0  | 1      | itemreceived | 2012-06-01
1  | 1      | modelyear    | 1992
2  | 1      | model        | 2
3  | 2      | itemreceived | 2012-06-05
4  | 2      | modelyear    | 2003
5  | 2      | model        | 1
6  | 3      | itemreceived | 2012-07-05
7  | 3      | modelyear    | 2000
8  | 3      | model        | 3

我当前的查询如下所示:

SELECT items.*, item_specs.* FROM item_specs
INNER JOIN item_specs ON items.itemId = item_specs.itemId
WHERE itemId IN(1,2,3)

如何按键值对结果进行排序,例如:模型?

我正在寻找的结果是这样的:(如果我按型号订购)

id | itemId | key          | values
---|--------|---------------
3  | 2      | itemreceived | 2012-06-05
4  | 2      | modelyear    | 2003
5  | 2      | model        | 1
0  | 1      | itemreceived | 2012-06-01
1  | 1      | modelyear    | 1992
2  | 1      | model        | 2
6  | 3      | itemreceived | 2012-07-05
7  | 3      | modelyear    | 2000
8  | 3      | model        | 3

返回的内容按具有键模型的值排序

4

4 回答 4

1
SELECT * FROM `table` WHERE `key` = 'model' ORDER BY `values` ASC

您必须手动指定表类型/存储引擎。这在您提供的结构中看不到。在这里
阅读更多。

于 2012-07-12T14:53:50.497 回答
1

You need the model number for every row. You can do that with a join:

SELECT items.*, item_specs.* 
FROM item_specs
INNER JOIN item_specs ON items.itemId = item_specs.itemId
INNER JOIN item_specs aux ON (aux.key = 'model' and aux.itemID = item_specs.itemId)
WHERE item_specs.itemId IN(1,2,3)
ORDER BY aux.values/*this is the model*/, item_specs.id;

or with a subselect:

SELECT items.*, 
       item_specs.*, 
       (select aux.values 
        from item_specs aux 
        where aux.key = 'model' and aux.itemID = item_specs.itemId
        ) as model
FROM item_specs
INNER JOIN item_specs ON items.itemId = item_specs.itemId
WHERE item_specs.itemId IN(1,2,3)
ORDER BY model, item_specs.id;
于 2012-07-13T08:07:25.303 回答
0

看来您想使用 order by 子句。这将按您需要的列排序。你也可以在这里做一些偷偷摸摸的事情,比如为你首先订购的东西插入一个真/假值。

SELECT * FROM `table` 
   Order by (case When Key='model' then 0 else 1 end), values

See, for instance, http://blog.sqlauthority.com/2007/07/17/sql-server-case-statement-in-order-by-clause-order-by-using-variable/

于 2012-07-12T15:08:26.840 回答
0
SELECT * FROM `table` 
WHERE `key` = 'model' 
ORDER BY `values`;
于 2012-07-12T15:27:44.173 回答