fl0*_*00r 2 mysql sql database join
我有表baskets
,fruits
和basket_fruits
(join-table :) basket_id-fruit_id
.
我怎样才能在篮子里找回每个水果的位置,这样我就会得到类似的东西
+---------------------------------------+
| basket_id | fruit_id | fruit_position |
|---------------------------------------|
| 1 | 2 | 1 |
| 1 | 5 | 2 |
+---------------------------------------+
Run Code Online (Sandbox Code Playgroud)
果实位置只是返回的连接表中的一行(它不是列).
Schema:
baskets: id, title
fruits: id, title
basket_fruits: id, basket_id, fruit_id
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
或使用会话变量(更快但依赖于未记录的实现细节,可能在将来的版本中中断):
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
Run Code Online (Sandbox Code Playgroud)