使用查询结果更新表

时间:2017-04-24 21:33:51

标签: mysql sql

在MySQL数据库中,我有以下表格

CREATE TABLE `store` (
  `ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `storetypeID` int(10) unsigned NOT NULL,
  `storename` varchar(100) NOT NULL,
  `VATnumber` char(9) NOT NULL,
  `visits` int(10) unsigned DEFAULT '0000000000',
  PRIMARY KEY (`ID`),
  UNIQUE KEY `ID_UNIQUE` (`ID`),
  UNIQUE KEY `VATnumber_UNIQUE` (`VATnumber`),
  KEY `storeID_idx` (`storetypeID`),
  CONSTRAINT `storeID` FOREIGN KEY (`storetypeID`) REFERENCES `storetype` (`ID`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=947 DEFAULT CHARSET=utf8;

CREATE TABLE `expenses` (
  `ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `storeID` int(10) unsigned DEFAULT NULL,
  `expensedate` date NOT NULL,
  `amount` decimal(10,2) NOT NULL,
  PRIMARY KEY (`ID`),
  UNIQUE KEY `ID_UNIQUE` (`ID`),
  KEY `storeID_idx` (`storeID`),
  CONSTRAINT `storeIDidx` FOREIGN KEY (`storeID`) REFERENCES `store` (`ID`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=7502 DEFAULT CHARSET=utf8;

使用以下查询,我得到每个商店的费用数量。

SELECT COUNT(*) AS visits, storeID FROM taxfriend.expenses GROUP BY storeID ORDER BY visits desc

有了这个结果,我想更新表存储中的字段访问,并从查询中进行字段访问。 一种选择是编写一个小子程序(例如使用VB)。

有没有办法在MySQL中创建UPDATE查询来实现这一目标?

2 个答案:

答案 0 :(得分:1)

您可以在UPDATE查询中使用UPDATE store AS s JOIN (SELECT COUNT(*) AS visits, storeID FROM taxfriend.expenses GROUP BY storeID) AS e ON s.ID = e.storeID SET s.visits = e.visits

<script type="text/javascript">
    $('#<%= TextBox1.ClientID %>').keyup(function () {
        var validator = document.getElementById('<%= RangeValidator1.ClientID %>');
        var errorMsg = 'Your value of ' + $(this).val() + ' is incorrect (max is ' + validator.maximumvalue + ')';
        $('#<%= RangeValidator1.ClientID %>').text(errorMsg);
    });
</script>

答案 1 :(得分:0)

update

中使用update store s join (SELECT COUNT(*) AS visits, storeID FROM taxfriend.expenses GROUP BY storeID ) sv on sv.storeId = s.id set s.visit = sv.visits;
public void Execute(IServiceProvider serviceProvider)
{
    IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
    context.InputParameters["CreateOpportunity"] = false;
}

这只会将值更新一次到当前数字。要使值保持最新,您需要使用触发器。

这就是为什么通常更好地计算这些值。当然,如果您的访问表非常大,那么触发器可能是保持价值最新的最佳方法。