2012-04-24 56 views
2

我有表baskets,fruitsbasket_fruits(連接表:basket_id-fruit_id)。加入職位

如何才能返回每個水果的位置,在籃下,所以我會得到什麼樣

+---------------------------------------+ 
| basket_id | fruit_id | fruit_position | 
|---------------------------------------| 
| 1   | 2  | 1    | 
| 1   | 5  | 2    | 
+---------------------------------------+ 

水果位置只是一個數字在返回連接錶行的(它不是列)。

Schema: 
baskets:  id, title 
fruits:  id, title 
basket_fruits: id, basket_id, fruit_id 
+0

您可以顯示模式? – Starx 2012-04-24 08:35:36

回答

5

MySQL不支持範圍功能,因此你必須使用子查詢:

SELECT basket_id, fruit_id, 
     (
     SELECT COUNT(*) 
     FROM basket_fruit bfi 
     WHERE bfi.basket_id = bf.basket_id 
       AND bfi.fruit_id <= bf.fruit_id 
     ) AS fruit_position 
FROM basket_fruit bf 
WHERE basket_id = 1 

或使用會話變量(速度較快,但依賴於未記錄的實施細則,並在將來的版本可能會中斷):

SET @rn = 0; 

SELECT basket_id, fruit_id, @rn := @rn + 1 AS fruit_position 
FROM basket_fruit bf 
WHERE basket_id = 1 
ORDER BY 
     fruit_id 
1

SQL對返回的行的順序沒有提供任何保證。因此,fruit_position不時查詢時可能會有所不同。由於桌面上的DML活動,最有可能發生這種情況。

如果你真的需要一些排序,你應該選擇:

  1. 使用現有列作爲排序鍵,如水果名稱(如果存在)
  2. 創建一個特殊的領域,像seq_nr將指定訂購了你的水果。
2

我沒有看到basket_fruits表中的任何列,我會考慮衡量。如果你只是想幾個電話號碼,該表添加到數據,你可以試試這個(這允許每個籃子都有自己的重量從1計數):

SET @current_group = NULL; 
SET @current_count = NULL; 

SELECT 
id, basket_id, fruit_id, 
CASE 
    WHEN @current_group = basket_id THEN @current_count := @current_count + 1 
    WHEN @current_group := basket_id THEN @current_count := 1 
END AS fruit_position 
FROM basket_fruits 
ORDER BY basket_id, id 

樣品輸入:

+----+-----------+----------+ 
| id | basket_id | fruit_id | 
+----+-----------+----------+ 
| 2 |   2 |  5 | 
| 6 |   2 |  1 | 
| 9 |   1 |  2 | 
| 15 |   2 |  3 | 
| 17 |   1 |  5 | 
+----+-----------+----------+ 

輸出示例:

+----+-----------+----------+----------------+ 
| id | basket_id | fruit_id | fruit_position | 
+----+-----------+----------+----------------+ 
| 9 |   1 |  2 |    1 | 
| 17 |   1 |  5 |    2 | 
| 2 |   2 |  5 |    1 | 
| 6 |   2 |  1 |    2 | 
| 15 |   2 |  3 |    3 | 
+----+-----------+----------+----------------+ 
+0

我在寫標題時正在考慮重量,但後來我忘了它:)謝謝你回答。去嘗試一下 – fl00r 2012-04-24 09:21:41