我需要一个查询来更新select(计数)语句中的列。
这是我尝试过的。
SELECT m.MaidID, m.MaidJobCompleted, count(m.MaidName) as countMaidJobCompleted
FROM Booking b, Maid m
WHERE b.BookingMaidID like concat("%",m.MaidName,"%")
and b.BookingStatus="completed"
group by MaidName
获得正确的结果:
MaidID MaidJobCompleted countMaidJobCompleted
329 0 5
188 0 1
281 0 8
229 0 4
MaidJobCompleted
是我创建的列(默认值为0)。
countMaidJobCompleted
是上面查询的列。
表格
女仆
MaidIDPrimary int(100) ,autoIncrement eg(1,2,3,4,5..)
MaidJobCompleted int(100) ,default value = 0
MaidName varchar(200) ,eg(Batman,Spiderman,WonderWoman,Indiana John)
预订
BookingID int(100) ,autoIncrement eg(1,2,3,4,5..)
BookingMaidID varchar(500) ,eg(Batman,Wonderwoman,Ironman)
BookingStatus varchar(50) ,eg(completed,pending..)
MaidID MaidJobCompleted countMaidJobCompleted
329 0 5
188 0 1
281 0 8
229 0 4
现在,我想使用UPDATE查询根据'countMaidJobCompleted'更新'MaidJobCompleted'列。
答案 0 :(得分:1)
首先,您应该标准化表。这意味着很多事情,但是在您的上下文中,我看到在表Maid中,需要计算列MaidJobCompleted
。这是禁忌。您最终可能会获得不同步的值(例如,新的预订已完成,但该计算的值未更新)。但是有一种方法可以确保不会发生这种情况。继续阅读...
另一个问题,BookingMaidID应该是一个数字,该数字是Maid表中MaidID的前键。您正在将名称与ID混合在一起。
我向您建议的是:
女仆表:
MaidID int(100) -- autoIncrement
MaidName varchar(200) -- some name
预订表:
BookingID int(100) -- autoIncrement
MaidID int(100) -- foreign-key to Maid:MaidID
StatusID int(100) -- foreign-key to Status:StatusID
状态表:
StatuID int(100) -- autoIncrement
StatusName varchar(200) -- some values, ex.completed,pending..
详细信息:
如果您需要知道所有女佣已经完成了多少预订,请使用以下方法:
SELECT b.MaidID, m.MaidName, COUNT(b.BookingID)
FROM Booking AS b
JOIN Maid AS m ON b.MaidID = m.MaidID
JOIN Status AS s ON b.StatusID = s.StatusID
WHERE b.StatusID = (SELECT StatusID FROM Status WHERE StatusName = 'Completed')
或者,如果您需要了解1个特定的女仆,请像这样修改它:
SELECT COUNT(b.BookingID)
FROM Booking AS b
JOIN Maid AS m ON b.MaidID = m.MaidID
JOIN Status AS s ON b.StatusID = s.StatusID
WHERE b.StatusID = (SELECT StatusID FROM Status WHERE StatusName = 'Completed')
AND m.MaidName = 'THE-NAME-YOU-WANT'
让我们稍微解释一下该查询:
免责声明,我直接在此处输入查询,而未在示例数据库上进行测试。
答案 1 :(得分:0)
将int
表与原始查询(成为子查询)一起加入,然后使用for comp in range(numComp):
更新您的maid
列:
countMaidJobCompleted