這是要解決的問題。我有一個表USERS和一個表GROUP_USER。我正在更新表用戶,我在該表中更新的資料將直接影響GROUP_USER表。這是表格
**Users table**
id
number_of_items
group_type //**group_type** value from GROUP_USER table
current_group //id column value from GROUP_USER table
**Group_user table**
id
group_type
item_count
//Query to update users table
"UPDATE users SET number_of_items = number_of_items - 1 WHERE item_type = :item AND number_of_items > 0"
我想要的是...如果從USERS表中的number_of_items列中減去 (1) 項后,余數等于零 (0),然后從GROUP_USER表中的'item_count'列中減去 (1) 的值WHERE group_type in GROUP_USER表等于USERS表中的current_group。因此,對于每個達到零的 number_of_items,它將根據它們所屬的 group_type 從 Group_user 表中減去 1。
一個類似的查詢,如果可能的話:
UPDATE
users a
SET
a.number_of_items = a.number_of_items - 1
WHERE
a.item_type = :item AND a.number_of_items > 0
(
if a.number_of_items - 1 = 0
UPDATE
group_user b, users a
SET
b.item_count - 1
WHERE
b.id = a.current_group
)
我可能不得不單獨運行下一個查詢,但如果 current_group 為 0,它會將所有用戶 number_of_items 更新為 0。抱歉,它有點復雜。
UPDATE
users
SET
current_group = 0
WHERE
number_of_items = 0
uj5u.com熱心網友回復:
LEFT在UPDATE陳述句中使用表的連接:
UPDATE users u
LEFT JOIN group_user g
ON g.id = u.current_group AND u.number_of_items = 1
SET u.number_of_items = u.number_of_items - 1,
g.item_count = g.item_count - 1
WHERE u.item_type = :item AND u.number_of_items > 0;
也許ON連接子句中的條件還需要包括列group_type:
ON g.id = u.current_group AND g.group_type = u.group_type AND u.number_of_items = 1
uj5u.com熱心網友回復:
如果您只更新用戶表中的一條記錄,那么您可以使用變數。您的查詢將是:
SET @ID = 0;
SET @C = 0;
UPDATE
users a
SET
a.number_of_items = @C := a.number_of_items - 1,
current_group = @ID := current_group
WHERE
a.item_type = :item AND a.number_of_items > 0
;
UPDATE
group_user
SET
item_count - 1
WHERE
(@C = 0) AND (id = @ID)
;
我使用了兩個變數@ID, @C,這些變數將保存用戶表中的值,然后我在第二個查詢中使用它們。請注意,第二個查詢僅在@C=0.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/529134.html
