按关系排序的多对多

时间:2013-09-05 17:51:39

标签: mysql sql

我有以下表格:

+---------+    +-----------+     +---------+
| USER    |    | USER_BOX  |     | BOX     |
| id      |    | user_id   |     | id      |
| name    |    | box_id    |     | name    |
|         |    |           |     |         |
+---------+    +-----------+     +---------+

我想要做的是查询数据库以列出所有框,但是让所有与用户关系的框首先列出,只列出。我被卡住了,我甚至不确定MySql是否支持这样的查询。

        USER                    BOX                 USER_BOX
+--------|--------+      +--------|--------+   +--------|--------+
|   0    | Jonh   |      |   0    | Boobox |   |   0    |    4   |
+--------|--------+      |   1    | RedBox |   |   0    |    3   | 
                         |   2    | GGbox  |   +--------|--------+
                         |   3    | OKbox  |   
                         |   4    | boxy   |   
                         +--------|--------+

结果查询应该返回:

4 - boxy
3 - Okbox
0 - Boobox    
1 - RedBox
2 - GGbox

编辑:我们的想法是能够按用户进行查询,因此更容易在大型列表中找到用户框。

3 个答案:

答案 0 :(得分:1)

SELECT b.id, b.name
FROM BOX b
LEFT JOIN (
    USER_BOX ub
    JOIN USER u ON (user_id = u.id)
) ON (box_id = b.id)
ORDER BY
    u.id IS NULL,
    b.id DESC

http://sqlfiddle.com/#!2/a4f304/4/0

编辑:实际上没有必要加入USER http://sqlfiddle.com/#!2/a4f304/7/0

答案 1 :(得分:0)

这样的事情:

SELECT a.id, a.name
FROM BOX AS a
LEFT JOIN USER_BOX AS b
 ON a.id = b.box_id
ORDER BY CASE WHEN b.box_id IS NOT NULL THEN 0 ELSE 1 END
      ,a.id

答案 2 :(得分:0)

SELECT * FROM BOX
WHERE box_id IN (SELECT box_id FROM USER_BOX)
UNION ALL
SELECT * FROM BOX
WHERE box_id NOT IN (SELECT box_id FROM USER_BOX)