我有两个名为历史和历史详细信息的表。历史记录表按月提供健身房访问次数,因此有重复的用户。我想更新历史详细信息表以反映用户访问健身房的月份。我更新了历史详细信息表,使用户名称唯一,因此没有重复项。以下是我在历史详细信息表中尝试实现的示例。
历史
|健身房使用|月|
|琼斯|四月|
|史密斯|四月|
|琼斯|三月|
|琼斯| Febru |
|史密斯| Janua |
历史详情
|健身房使用| Jan |二月| Mar |四月|
|琼斯_ | _ | X | X | X |
|史密斯_ | X | _ | _ | X |
答案 0 :(得分:1)
只需进行数据透视查询:
SELECT `Gym Use`,
min(IF( `Month` = 'April', 'X', '_' )) As April,
min(IF( `Month` = 'March', 'X', '_' )) As March,
min(IF( `Month` = 'Febru', 'X', '_' )) As Febru,
min(IF( `Month` = 'Janua', 'X', '_' )) As Janua
FROM history
GROUP BY `Gym Use`
演示:http://sqlfiddle.com/#!9/f71c5/1
并在多表更新中使用此查询的结果:
UPDATE `history detail` h, (
SELECT `Gym Use`,
min(IF( `Month` = 'April', 'X', '_' )) As April,
min(IF( `Month` = 'March', 'X', '_' )) As March,
min(IF( `Month` = 'Febru', 'X', '_' )) As Febru,
min(IF( `Month` = 'Janua', 'X', '_' )) As Janua
FROM history
GROUP BY `Gym Use`
) x
SET h.April = x.April, h.March = x.March, h.Febru = x.Febru, h.Janua = x.Janua
WHERE h.`Gym Use` = x.`Gym Use`
答案 1 :(得分:0)
UPDATE history_detail SET Jan='X'
WHERE Gym_User IN (SELECT Gym_User FROM history WHERE Month='Janua');
UPDATE history_detail SET Feb='X'
WHERE Gym_User IN (SELECT Gym_User FROM history WHERE Month='Febru');
等