【问题标题】:How to create a index in MYSQL?如何在 MYSQL 中创建索引?
【发布时间】:2018-01-25 06:44:44
【问题描述】:

我有一个这样的 sql 查询:

 Select ah.CODE,
          case when ( (t.narration)='' OR (t.narration) is NULL) then concat(isnull(v.nameandaddress,''),' ', (v.remarks)) else (t.narration) end as narration, 
          v.VOUCHERNO,  
          case when t.CREDITDEBIT = 1 then t.amount else 0 end as dr_amount,  
          case when t.CREDITDEBIT = 0 then t.amount else 0 end as cr_amount,  
          v.issueDate,
          ag.NAME , 
          ah.name, 
          (v.remarks) 
from voucher v   
inner join transactiondetails t on t.tx_voucher_id = v.voucherId and 
t.tx_voucher_branch = v.sourceUnit  
inner join accounthead ah on t.accounthead_id = ah.ID  
inner join accountgroup ag on ag.ID=ah.accountgroup_id  
 where v.sourceunit=279 
   and v.issueDate between '2017-04-01 00:00:00' and '2018-01-18 00:00:00' 
   and v.ISCANCELLED=0 
   and ah.code in ('1412')  
order by ah.name, v.issuedate, v.voucherid

如果我给表 transactiondetails 一个索引,它会帮助这个查询吗?

创建的索引如下所述

CREATE INDEX IDX_transactiondetails_ID_Branch ON  transactiondetails 
(tx_voucher_id,tx_voucher_branch,accounthead_id) INCLUDE 
 (narration,CREDITDEBIT,amount)

从上面的索引创建查询中,我们对某些列使用了 INCLUDE 关键字。现在我需要知道,如何在 MySQL 中创建上述索引创建查询?

【问题讨论】:

  • mysql 不支持INCLUDE,如SQL Server。您必须改为包含所有列名。 CREATE INDEX IDX_transactiondetails_ID_Branch ON transactiondetails (tx_voucher_id,tx_voucher_branch,accounthead_id,narration,CREDITDEBIT,amount)
  • 提示:ANSI SQL 标准中没有提到索引!每个品牌的 SQL 数据库都以自己的方式实现索引,作为特定于供应商的 SQL 扩展。因此,您确实需要了解您使用的数据库产品支持的语法和功能,不要假设适用于 Microsoft 的语法适用于任何其他品牌。

标签: mysql sql mysql-workbench


【解决方案1】:

试试这个:

CREATE INDEX IDX_transactiondetails_ID_Branch ON  transactiondetails (tx_voucher_id, tx_voucher_branch, accounthead_id, narration, CREDITDEBIT, amount)

MySQL 不支持“INCLUDE”,所以必须创建多列索引。

在这里阅读更多: https://dev.mysql.com/doc/refman/5.7/en/multiple-column-indexes.html

【讨论】:

  • 感谢您提供此代码 sn-p,它可能会提供一些有限的即时帮助。 proper explanation would greatly improve its long-term value 通过展示为什么这是一个很好的解决问题的方法,并将使其对未来有其他类似问题的读者更有用。请edit您的回答添加一些解释,包括您所做的假设。
  • 这种在 MySQL 中创建索引的美妙之处在于它也与 H2 兼容。谢谢!我的嵌入式数据库测试再次工作!
猜你喜欢
  • 2012-04-23
  • 1970-01-01
  • 1970-01-01
  • 2012-11-26
  • 2013-06-22
  • 2016-11-18
  • 1970-01-01
  • 1970-01-01
  • 2019-04-26
相关资源
最近更新 更多