0

我有以下表格:

+---------+    +-----------+     +---------+
| 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

编辑:这个想法是能够按用户查询,因此更容易在大列表中找到用户框。

4

3 回答 3

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

于 2013-09-05T18:03:21.310 回答
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)
于 2013-09-05T18:06:42.810 回答
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
于 2013-09-05T17:56:46.290 回答