Mysql
MySQL - 來自 SELECT 的更新
我越了解你可以用 mysql 做的偉大事情,我就越努力學習。
我有兩張桌子:
測試
TestNumber (int primary key) InactiveTestSlotBitwise (int)
測試使用者
UserId (int) TestNumber (int - ties in with the TestNumber in Tests) UserSlot (int the person's seating position in the test)
我一直在 php 中分兩個階段執行以下操作,但現在認為這很麻煩。我正在收集 UserId = 25 的所有“TestUsers”並返回到 php 程式碼,該程式碼然後單獨呼叫數據庫,然後更改“Tests”中的“InactiveTestSlotBitwise”以顯示他們已將自己從測試中刪除在。
但是,現在我認為我應該在一次通話中做其他事情,如下:
UPDATE tests AS t SET t.InactiveTestSlotBitwise = (t.InactiveTestSlotBitwise | (1 << tu.UserSlot)) FROM (SELECT TestNumber, UserSlot FROM testusers WHERE UserId=25 AND UserSlot >= 0 ) AS tu WHERE t.TestNumber= tu.TestNumber
這肯定是可能的嗎?它不喜歡它,但確實說出了原因。它說:
‘您的 SQL 語法有錯誤;檢查與您的 MySQL 伺服器版本相對應的手冊,以在“FROM (SELECT TestNumber, UserSlot …”附近使用正確的語法
MySQL 沒有 for 的語法
UPDATE ... FROM
,但它確實允許UPDATE table1, table2,... SET table1.col = value WHERE table1.id = table2.id
. 您可以嘗試以下方法:UPDATE Tests AS t, (SELECT TestNumber, UserSlot FROM TestUsers WHERE UserId=25 AND UserSlot >= 0) AS tu SET t.InactiveTestSlotBitwise = (t.InactiveTestSlotBitwise | (1 << tu.UserSlot)) WHERE t.TestNumber= tu.TestNumber;
嘗試以下操作:
UPDATE tests AS t JOIN testusers AS tu ON t.TestNumber= tu.TestNumber SET t.InactiveTestSlotBitwise = (t.InactiveTestSlotBitwise | (1 << tu.UserSlot)) WHERE tu.UserId=25 AND tu.UserSlot >= 0;