DataBase

浏览模式: 标准 | 列表 | 图文
一句SQL:取得相同sortid的结果集,每种 ID三条数据

一句SQL:取得相同sortid的结果集,每种 ID三条数据

一个表:

CREATE TABLE `book` (
`bookid` int(11) unsigned NOT NULL AUTO_INCREMENT,
`sortid` int(11) NOT NULL,
`bookname` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`bookid`)
) ENGINE=InnoDB AUTO_INCREMENT=80729 DEFAULT CHARSET=utf8;

数据是这样的:

insert into `book`(`bookid`,`sortid`,`bookname`) values (1,1,'1'),(2,1,'2'),(3,1,'3'),(4,1,'4'),(5,2,'1'),(6,2,'2'),(7,2,'3'),(8,2,'4'),(9,2,'5'),(10,2,'6'),(11,2,'7'),(12,2,'8'),(13,2,'9'),(14,2,'10'),(15,2,'11'),(16,3,'1'),(17,3,'2'),(18,3,'3'),(19,3,'4'),(20,3,'5'),(21,3,'6'),(22,3,'7'),(23,3,'8'),(24,3,'9'),(25,3,'10'),(26,3,'11'),(27,3,'12'),(28,4,'1'),(29,4,'2'),(30,4,'3'),(31,4,'4'),(32,4,'5'),(33,5,'1'),(34,5,'2'),(35,5,'3'),(36,5,'4');

在这种情况下,要取得 sortid IN (1,2,3)的数据,每个sortid的结果是3条。
这种题目网上很多,但真的没有一种特别好SQL,在网上有很多种。最初的时候,我自己是想着用union来处理,但最终这种方法太伤了,同事clear提出的SQL不错,试了一下,在几万条数据的时候,效率还可以,而且SQL相对简单:

SELECT sortid,bookname FROM book b WHERE sortid IN(1,2) AND 3>(SELECT COUNT(1) FROM book WHERE b.sortid=sortid AND bookid<b.bookid)

表自关联,在sortid上建索引,效率还不错。

一句可以围观的SQL

窝窝(Walkerlee)最近说他折腾了一个SQL,提升了他的工作效率。表示要到博客来投稿,今天我把这个SQL放出来了。
嗯。我总不能说,因为我确实会这个SQL就断了他投稿的心,否则他会砍我的。

前因:
数据库结构如下:

要求:一句SQL实现,分别统计type1,2,3,4 一共多少money (group by uid)

原先做法:分开查询 然后用php合并结果,如

select sum(money) form test where type = 1 group by uid
select sum(money) form test where type = 2 group by uid
select sum(money) form test where type = 3 group by uid
select sum(money) form test where type = 4 group by uid

现在要求一句SQL。
窝窝问我的时候,我说if(a,b,c)这个函数可以解决,于是他很愤怒。。。。
贴出了最终的SQL语句:

SELECT
uid,
SUM( IF(`type`=1, money, 0 ) ) AS `BuyByCash`,
SUM( IF (`type`=3, money, 0 ) ) AS `BuyByCard`,
SUM( IF( `type` IN (1,3), money, 0 ) ) AS `BuyByCashAndCard`,
SUM( IF(`type`=2, money, 0 ) ) AS `SellByCash`,
SUM( IF(`type`=4, money, 0 ) ) AS `SellByCard`,
SUM( IF( `type` IN (2,4), money, 0 ) ) AS `BuyByCashAndCard`,
SUM(money) AS `Amount`,
COUNT(*) AS `DataNums`
FROM `test`
group by `uid`

窝窝比较郁闷,因为以前处理起来很麻烦,而现在一句就解决了。


此事完结后,他又介绍了一个小技巧:
我有一个relation表,用来存储订单下面的游客

ALTER TABLE `travel_order_customer_relation`
ADD CONSTRAINT `travel_order_customer_relation_ibfk_1` FOREIGN KEY (`oid`) REFERENCES `travel_orders` (`id`) ON DELETE CASCADE;

然后我用了一个外键,这样order被删除时候,这个关系表里面的相关数据也就自动删除了
----
然后我也很郁闷的说,我的数据表不是INNODB的,所以这个功能我不能用。。。也很纠结

Infomation:WebKit Does HTML5 Client-side Database Storage

资料备份,其中有两个链接很重要 :
原资料中的:client-side database storage.已经打不开了,好象是换成这个了:10.1.2.2 A worker for updating a client-side database
但我也说不准,详情还是看这个页面吧:http://www.whatwg.org/specs/web-apps/current-work/multipage/

对了,因为是基于webkit的,所以,FF上是没法用的。更多的还是用于ipad,iphone之类的上面吧。

jQueryMobile的代码里应该是有了

WebKit Does HTML5 Client-side Database Storage

Posted by Brady Eidson on Friday, October 19th, 2007 at 4:04 pm

The current working spec for the HTML5 standard has a lot of exciting features we would eventually like to implement in WebKit. One feature we felt was exciting enough to tackle now even though the spec is still in flux is client-side database storage. So for the last few weeks andersca, xenon, and I have been cooking up an implementation!

The client-side database storage API allows web applications to store structured data locally using a medium many web developers are already familiar with – SQL.

The API is asynchronous and uses callback functions to track the results of a database query.
Compact usage defining a callback function on the fly might look something like this:

var database = openDatabase("Database Name", "Database Version");

database.executeSql("SELECT * FROM test", function(result1) {
// do something with the results
database.executeSql("DROP TABLE test", function(result2) {
// do some more stuff
alert("My second database query finished executing!");
});
});

There will also be a small example of how to use the API in a real site that we’ll try to keep up to date as things evolve.

This initial implementation has some things missing from the spec as well as a few known bugs. But it does the basics and the best way to discover what needs work is to get it out there for people to start using it!

If you find any bugs, would like to suggest features, or have gripes about the spec itself, please drop by #webkit or drop us a line on the WebKit email lists.

Oh, and one more thing…

We’re landing this initial implementation with pretty cool Web Inspector support!
So far you can view the full contents of any table and run arbitrary queries on each database a page is using. We have a lot of ideas for improvements but would also love to hear yours.
DatabaseInspector

转:极速理解设计模式系列【目录索引】

转:极速理解设计模式系列【目录索引】

这里是一个文件索引,如果对设计模式感兴趣可以打开看看。
是同一个作者写的东西,也是他自己整理出来的索引,所以可以尝试一观,当然你可以从第一篇开始看,如果觉得兴趣不大,或者不对你的胃口,就可以咔嚓了。
作者是程兴亮。

这是一个老生常谈的设计模式系列文章,本系列力图从最简洁的语言和最易理解的实例来让大家认识设计模式的思想和思路,从而在实际项目中能够用到一二。现在将本系列文章详列如下:

极速理解设计模式系列:1.建造者模式(Builder Pattern)

极速理解设计模式系列:2.观察者模式(Observer Pattern)

极速理解设计模式系列:3.代理模式(Proxy Pattern)

极速理解设计模式系列:4.原型模式(Prototype Pattern)

极速理解设计模式系列:5.组合模式(Composite Pattern)

极速理解设计模式系列:6.适配器模式(Adapter Pattern)

极速理解设计模式系列:7.桥接模式(Bridge Pattern)

极速理解设计模式系列:8.策略模式(Strategy Pattern)

极速理解设计模式系列:9.工厂方法模式(Factory Method Pattern)

极速理解设计模式系列:10.抽象工厂模式(Abstract Factory Pattern)

极速理解设计模式系列:11.单例模式(Singleton Pattern)

极速理解设计模式系列:12.责任链模式(Chain of Responsibility Pattern)

极速理解设计模式系列:13.外观模式(Facade Pattern)

极速理解设计模式系列:14.轻量级模式(Flyweight Pattern)

极速理解设计模式系列:15.中介者模式(Mediator Pattern)

极速理解设计模式系列:16.迭代器模式(Iterator Pattern)

极速理解设计模式系列:17.命令模式(Command Pattern)

极速理解设计模式系列:18.访问者模式(Visitor Pattern)

设计模式这东西,本来就是属于通用的玩意,因此不用纠结语言,随便看看。
同时,也别过多的纠结这些,这些只是进阶的玩意,如果你连基础的代码都写不来也别看这些了,有意义吗??
其实我也看不懂,好吧

update sql

update sql

更新数据库的时候,提示: You can't specify target table 'channels' for update in FROM clause
出错的SQL是什么呢?
出错的是SQL是:
update channels set parentid = 0 where parentid in (select b.id from channels b where b.parentid = 0) ;
从理论上来看好象没什么错,但就是出现上面的错误(You can't specify target table 'channels' for update in FROM clause),说是不能在原表操作。于是改正它。。
改成:
update channels set parentid = 0 where parentid IN ( select id from (SELECT id from channels where parentid = 0) as tmp )
看上去是不是很恶心?但确实是通过临时表来解决了这个问题。。。
好吧,我又恶心了

mysql子查询删除

mysql子查询删除

这是我试了很多的代码之后才。。。。
#select id,count(1) as cnt from feeds_datas group by link HAVING count(1) > 7 order by cnt DESC
#delete from feeds_datas where link = (select link from feeds_datas WHERE id in ()
#delete from feeds_datas where id in (6697,7127,6798,4557,4558,6086,6087,6088,6089)
#select id from feeds_datas group by link HAVING count(link) > 1

#delete from feeds_datas as a WHERE a.in in (select b.id from feeds_datas as b group by b.link HAVING count(b.link) > 1 )
#delete from feeds_datas t1,(select link from feeds_datas group by link HAVING count(1) > 1) t2 where t1.link = t2.link

#and id not in (select min(id) from feeds_datas group by link having count(link )>1)

delete feeds_datas as a from feeds_datas as a,
(
select *,min(id) from feeds_datas group by link having count(1) > 1
) as b
where a.link = b.link and a.id > b.id;

加#的都是失败的,其中最后一条SQL我很纳闷,如果把delete 后面的 feeds_datas as a去掉,那么sql就报错,说是不许right syntax之类的。加上就OK。
记录一下。。
网上有很多资料,可以参考:
1、http://yueliangdao0608.blog.51cto.com/397025/81390
2、http://zhidao.baidu.com/question/85817899

mysql:Lost connection to MySQL server at 'reading initial communication packet', system error: 0

远程管理数据库的时候,以前都是用phpmyadmin,后来就再也不用这种了,一来是因来速度慢,二来扔在服务器上,人人都可以访问太危险了。。所以我现在在用navicat的ssh方式访问。其实我比较喜欢用SQLyog的,但是它没有mac的版本。
OK,现在我们开始用nvaicat来访问吧。
一台服务器正常了,二台正常了,结果,第三台不正常了。报错:

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

然后找资料了。
1、有人说,在mysqld启动的时候加入skip-name-resolve,于是我在my.cnf加上,也没用。。。
2、又有人说,需要在/etc/hosts.allow里加上mysqld:allow,好吧,我继续加上,仍然没用。参考:http://www.bramschoenmakers.nl/en/node/595
3、最后找不同点。突然发现,原来连接不上的那台服务器的my.cnf里居然有一个bind-address:xx.xxx.xxx.xxx,绑定了IP,所以ssh通道连接的时候,不能工作,改成127.0.0.1后一切正常

4、结果改完后发现,本地代码连接远程的时候,连接不上数据库了,代码里写死IP的所以无法改变。最终再找资料把bind-address改为0.0.0.0,然后一切都正常了(这个只适合在局域网测试上,其他情况下尽量不要改,出了问题可不要找我。。。。)

c66720f398993c1dafe0295badd54360

77faef8027abdd27d3c2abbdddf26b4d

1d7fc10e02936c998df4cbb0756b3038

60599e1da023fd13adcc616cf3292b9f

553b8040361490dbc14e42b4d4c008bb

6c0bab963671a2696e7f302b8a8cc0ea

震精:[图]MySQL.com被黑 黑客挂牌出售其root权限

震精:[图]MySQL.com被黑 黑客挂牌出售其root权限

在cnbeta上看到这个新闻的时候,震精了啊。
新闻不知道是真是假,所以我纯转贴,莫找我啊,原文来自:http://www.cnbeta.com/articles/156424.htm

Amorize的安全研究人员最近表示,已经确认黑客入侵mysql.com,并通过iframe的方法让用户感染了恶意代码,他们已经追踪到佛罗里达和瑞典两个恶意软件托管地,在当地时间周一下午依然在对mysql.com的访客实施攻击,用户凭据可能已经遭到了窃取,因此建议mysql.com注册过的用户修改自己与此相同的密码。

更糟的是研究发现,mysql.com的root权限似乎已经开始在俄罗斯的地下黑客论坛挂牌出售,价格3000美元,黑客们只要给钱就可以获得访问mysql.com的权限,可见问题的糟糕程度。

ef532ef234018a7991347efc69ce6aff

几个无限分类的设计

之前在博客里贴过无限分类的介绍,那是官方的例子,但上次在给同事们做介绍的时候,却发现官方的网站已经打不开了。所幸,又找到了一篇,好象这个才是原文?
原文来自:http://www.vbmysql.com/articles/database-design/managing-hierarchical-data-in-mysql
为了这次保证所有的数据都能够记录下来而不是再被茫茫的互联网淹没,所以我做了备份。
mysql.7z
但同样的,我也再次复制一部分的内容下来,好象是说这种无限分类的效率,在被其他项目查询的时候是最高的,但CRUD的时候就有点纠结。
OK,上主菜:

The Nested Set Model

What I would like to focus on in this article is a different approach, commonly referred to as the Nested Set Model. In the Nested Set Model, we can look at our hierarchy in a new way, not as nodes and lines, but as nested containers. Try picturing our electronics categories this way:

Nested Categories

Notice how our hierarchy is still maintained, as parent categories envelop their children.We represent this form of hierarchy in a table through the use of left and right values to represent the nesting of our nodes:

CREATE TABLE nested_category (         category_id INT AUTO_INCREMENT PRIMARY KEY,         name VARCHAR(20) NOT NULL,         lft INT NOT NULL,         rgt INT NOT NULL );  INSERT INTO nested_category VALUES(1,'ELECTRONICS',1,20),(2,'TELEVISIONS',2,9),(3,'TUBE',3,4),  (4,'LCD',5,6),(5,'PLASMA',7,8),(6,'PORTABLE ELECTRONICS',10,19),(7,'MP3 PLAYERS',11,14),(8,'FLASH',12,13),  (9,'CD PLAYERS',15,16),(10,'2 WAY RADIOS',17,18);  SELECT * FROM nested_category ORDER BY category_id;  +-------------+----------------------+-----+-----+ | category_id | name                 | lft | rgt | +-------------+----------------------+-----+-----+ |           1 | ELECTRONICS          |   1 |  20 | |           2 | TELEVISIONS          |   2 |   9 | |           3 | TUBE                 |   3 |   4 | |           4 | LCD                  |   5 |   6 | |           5 | PLASMA               |   7 |   8 | |           6 | PORTABLE ELECTRONICS |  10 |  19 | |           7 | MP3 PLAYERS          |  11 |  14 | |           8 | FLASH                |  12 |  13 | |           9 | CD PLAYERS           |  15 |  16 | |          10 | 2 WAY RADIOS         |  17 |  18 | +-------------+----------------------+-----+-----+

We use lft and rgt because left and right are reserved words in MySQL, see http://dev.mysql.com/doc/mysql/en/reserved-words.html for the full list of reserved words.

So how do we determine left and right values? We start numbering at the leftmost side of the outer node and continue to the right:

Numbering edges

This design can be applied to a typical tree as well:

Numbered Tree

When working with a tree, we work from left to right, one layer at a time, descending to each node’s children before assigning a right-hand number and moving on to the right. This approach is called the modified preorder tree traversal algorithm.

因为我已经在压缩包里做了备份,所以我图片就引用外站的了。

转:geohash-用字符串实现附近地点搜索

转:geohash-用字符串实现附近地点搜索

依稀记得MYSQL5开始支持经纬度了,但在项目中没用过,所以现在也记不清是否有此功能了,不过今天看到这篇文章的时候,感觉这样的处理方法也不错。
原文来自:http://tech.idv2.com/2011/07/05/geohash-intro/

上回说到了用经纬度范围实现附近地点搜索。 一些小型应用中这样做没问题,但在大型应用中它有个显著的缺点:速度慢。慢的原因有两个, 第一是范围比较的索引利用率并不高,第二是SQL语句极其不稳定(不同的当前位置会产生完全不同的SQL查询),很难缓存。

可以考虑使用geohash算法。

geohash是一种地址编码,它能把二维的经纬度编码成一维的字符串。比如,北海公园的编码是wx4g0ec1。

52ef2f324dd2fe69be5745a6d1100535

geohash有以下几个特点:

首先,geohash用一个字符串表示经度和纬度两个坐标。某些情况下无法在两列上同时应用索引 (例如MySQL 4之前的版本,Google App Engine的数据层等),利用geohash,只需在一列上应用索引即可。

其次,geohash表示的并不是一个点,而是一个矩形区域。比如编码wx4g0ec19,它表示的是一个矩形区域。 使用者可以发布地址编码,既能表明自己位于北海公园附近,又不至于暴露自己的精确坐标,有助于隐私保护。

第三,编码的前缀可以表示更大的区域。例如wx4g0ec1,它的前缀wx4g0e表示包含编码wx4g0ec1在内的更大范围。 这个特性可以用于附近地点搜索。首先根据用户当前坐标计算geohash(例如wx4g0ec1)然后取其前缀进行查询 (SELECT * FROM place WHERE geohash LIKE 'wx4g0e%'),即可查询附近的所有地点。

74361358ea9b27190a74c77ea7352347

geohash的算法

下面以(39.92324, 116.3906)为例,介绍一下geohash的编码算法。首先将纬度范围(-90, 90)平分成两个区间(-90, 0)、(0, 90), 如果目标纬度位于前一个区间,则编码为0,否则编码为1。由于39.92324属于(0, 90),所以取编码为1。然后再将(0, 90)分成 (0, 45), (45, 90)两个区间,而39.92324位于(0, 45),所以编码为0。以此类推,直到精度符合要求为止,得到纬度编码为1011 1000 1100 0111 1001。

纬度范围 划分区间0 划分区间1 39.92324所属区间
(-90, 90) (-90, 0.0) (0.0, 90) 1
(0.0, 90) (0.0, 45.0) (45.0, 90) 0
(0.0, 45.0) (0.0, 22.5) (22.5, 45.0) 1
(22.5, 45.0) (22.5, 33.75) (33.75, 45.0) 1
(33.75, 45.0) (33.75, 39.375) (39.375, 45.0) 1
(39.375, 45.0) (39.375, 42.1875) (42.1875, 45.0) 0
(39.375, 42.1875) (39.375, 40.7812) (40.7812, 42.1875) 0
(39.375, 40.7812) (39.375, 40.0781) (40.0781, 40.7812) 0
(39.375, 40.0781) (39.375, 39.7265) (39.7265, 40.0781) 1
(39.7265, 40.0781) (39.7265, 39.9023) (39.9023, 40.0781) 1
(39.9023, 40.0781) (39.9023, 39.9902) (39.9902, 40.0781) 0
(39.9023, 39.9902) (39.9023, 39.9462) (39.9462, 39.9902) 0
(39.9023, 39.9462) (39.9023, 39.9243) (39.9243, 39.9462) 0
(39.9023, 39.9243) (39.9023, 39.9133) (39.9133, 39.9243) 1
(39.9133, 39.9243) (39.9133, 39.9188) (39.9188, 39.9243) 1
(39.9188, 39.9243) (39.9188, 39.9215) (39.9215, 39.9243) 1

经度也用同样的算法,对(-180, 180)依次细分,得到116.3906的编码为1101 0010 1100 0100 0100。

经度范围 划分区间0 划分区间1 116.3906所属区间
(-180, 180) (-180, 0.0) (0.0, 180) 1
(0.0, 180) (0.0, 90.0) (90.0, 180) 1
(90.0, 180) (90.0, 135.0) (135.0, 180) 0
(90.0, 135.0) (90.0, 112.5) (112.5, 135.0) 1
(112.5, 135.0) (112.5, 123.75) (123.75, 135.0) 0
(112.5, 123.75) (112.5, 118.125) (118.125, 123.75) 0
(112.5, 118.125) (112.5, 115.312) (115.312, 118.125) 1
(115.312, 118.125) (115.312, 116.718) (116.718, 118.125) 0
(115.312, 116.718) (115.312, 116.015) (116.015, 116.718) 1
(116.015, 116.718) (116.015, 116.367) (116.367, 116.718) 1
(116.367, 116.718) (116.367, 116.542) (116.542, 116.718) 0
(116.367, 116.542) (116.367, 116.455) (116.455, 116.542) 0
(116.367, 116.455) (116.367, 116.411) (116.411, 116.455) 0
(116.367, 116.411) (116.367, 116.389) (116.389, 116.411) 1
(116.389, 116.411) (116.389, 116.400) (116.400, 116.411) 0
(116.389, 116.400) (116.389, 116.394) (116.394, 116.400) 0

接下来将经度和纬度的编码合并,奇数位是纬度,偶数位是经度,得到编码 11100 11101 00100 01111 00000 01101 01011 00001。

最后,用0-9、b-z(去掉a, i, l, o)这32个字母进行base32编码,得到(39.92324, 116.3906)的编码为wx4g0ec1。

十进制 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
base32 0 1 2 3 4 5 6 7 8 9 b c d e f g
十进制 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
base32 h j k m n p q r s t u v w x y z

解码算法与编码算法相反,先进行base32解码,然后分离出经纬度,最后根据二进制编码对经纬度范围进行细分即可,这里不再赘述。 不过由于geohash表示的是区间,编码越长越精确,但不可能解码出完全一致的地址。

geohash的应用:附近地址搜索

geohash的最大用途就是附近地址搜索了。不过,从geohash的编码算法中可以看出它的一个缺点:位于格子边界两侧的两点, 虽然十分接近,但编码会完全不同。实际应用中,可以同时搜索当前格子周围的8个格子,即可解决这个问题。

以geohash的python库为例,相关的geohash操作如下:

>>> import geohash >>> geohash.encode(39.92324, 116.3906, 5)  # 编码,5表示编码长度 'wx4g0' >>> geohash.expand('wx4g0')                # 求wx4g0格子及周围8个格子的编码 ['wx4ep', 'wx4g1', 'wx4er', 'wx4g2', 'wx4g3', 'wx4dz', 'wx4fb', 'wx4fc', 'wx4g0']

最后,我们来看看本文开头提出的两个问题:速度慢,缓存命中率低。使用geohash查询附近地点,用的是字符串前缀匹配:

SELECT * FROM place WHERE geohash LIKE 'wx4g0%';

而前缀匹配可以利用geohash列上的索引,因此查询速度不会太慢。另外,即使用户坐标发生微小的变化, 也能编码成相同的geohash,这就保证了每次执行相同的SQL语句,使得缓存命中率大大提高。

相关资源