0

我有以下表格:

Collections ( 'id', 'name') 

(1, 'one collection')

ItemToCollection ( 'item_id', 'collection_id')

(1,1),
(2,1),
(3,1),
...etc

Items ( 'id', 'name' )

(1, 'one'),
(2, 'two'),
(3, 'three'),
(4, 'four'),
(5, 'five'),
(6, 'six'),
(7, 'seven')

CollectionsPositions ( 'col_id', 'item_id', 'pos' )

(1, 2, 2),
(1, 4, 7),
(1, 1, 4)

我想返回按 CollectionsPositions 中为 Collection 1 指定的顺序排序的项目,但问题是我没有所有项目的位置,并且无法使用 ORDER BY 为某些项目设置 NULL 值。

我正在尝试这样的事情:

SELECT FROM ItemToCollection 
JOIN Item ON ItemToCollection.item_id = Item.id
LEFT JOIN CollectionsPositions
       ON col_id = 1 AND item_id = ItemToCollection.item_id
WHERE ItemToCollection.collection_id = 1

这将返回给我这样的东西:列'pos':

NULL,
NULL,
NULL,
NULL,
NULL,
2,
4,
7

如何按以下顺序订购商品:?

NULL,
2,
NULL,
4,
NULL,
NULL,
7

我意识到我必须创建一个新列并按该列排序,但是当我生成新列进行排序时,如何处理已经定义的位置?

4

1 回答 1

2

试试这个(我已经在本地测试过,它可以工作):

SELECT
    tmp.pos
FROM (
    SELECT 
        CollectionsPositions.pos,
        IF( CollectionsPositions.pos IS NULL , 0, @c := CollectionsPositions.pos )
    FROM ItemToCollection 
    JOIN Item ON ItemToCollection.item_id = Item.id
    LEFT JOIN CollectionsPositions
           ON col_id = 1 AND item_id = ItemToCollection.item_id
    WHERE ItemToCollection.collection_id = 1
    ORDER BY
        IFNULL(CollectionsPositions.pos,@c)
) as tmp
于 2013-05-27T12:07:22.523 回答