巧解如何编写可重用的MySQL查询

 2022-10-27    448  

导读:当人们提及可重用的MySQL查询的时候,立即映入脑海的往往就是存储过程了。虽然这些存储过程是编写可重用代码不可分割的一部分,但要记住的是,它们只是很少的一部分而已,而非全部。此外,其它可重用代码包括视图、内置函数以及用户定义的函数。在本文中,我们将向读者详细介绍如何编写可重用的MySQL查询,以令我们的选择语句可以更好的适用于各种查询,也可以将MySQL查询的工作做的更好。

一、关于视图   视图的用途很多,例如简化复杂的模式及查询,或者提供安全性等等。视图提供安全性的一种途径是对开发者隐藏审计字段。视图还可通过减少列的数目来提高性能。这个想法是只引用索引字段,而索引字段的搜索速度是非常之快的。实际上,这种想法实现起来很费劲,因为你必须确保不会访问隐藏列。然而,我们这里主要是利用视图模拟两个或更多个表之间的连接,以降低查询的复杂性。很多时候,要想将数据库中用户的概要信息整理成符合第三范式的形式,可能需要多达六次连接操作,例如:select *   from Users u

巧解如何编写可重用的MySQL查询

  inner join UserPhoneNumbers upn on u.user_id = upn.user_id

  inner join UserScreenNames usn on u.user_id = usn.user_id

  inner join UserAffiliations ua on u.user_id = ua.user_id

  inner join Affiliations a on a.affiliation_id = ua.affiliation_id

  inner join UserWorkHistory uwh on u.user_id = uwh.user_id

  inner join Affiliations wa on uwh.affiliation_id = wa.affiliation_id

下面,我们用一个视图来替换上面的查找过程:

CREATE VIEW `vusers` AS   select *

  from Users u

  inner join UserPhoneNumbers upn on u.user_id = upn.user_id

  inner join UserScreenNames usn on u.user_id = usn.user_id

  inner join UserAffiliations ua on u.user_id = ua.user_id

  inner join Affiliations a on a.affiliation_id = ua.affiliation_id

  inner join UserWorkHistory uwh on u.user_id = uwh.user_id

  inner join Affiliations wa on uwh.affiliation_id = wa.affiliation_id;

现在,我们可以通过以下简单的选择语句来检索用户概要信息了:

select *   from vusers u

  where u.user_id = 100

#p#

二、

  •  标签:  
  • MySQL
  •  

原文链接:https://77isp.com/post/4230.html

=========================================

https://77isp.com/ 为 “云服务器技术网” 唯一官方服务平台,请勿相信其他任何渠道。