- 论坛徽章:
- 0
|
假设
用户表为 users, 主键为 userid
好友关系表为 friends 联合主键为 userid, friend_userid
则可以写作
select b.* from
friends a, users b
where a.userid = 某人id
and a.friend_userid = b ...
按照您说的办法我构建测试数据表结构如下:
- /*
- SQLyog Enterprise - MySQL GUI v6.0
- Host - 5.1.26-rc-community : Database - test
- *********************************************************************
- Server version : 5.1.26-rc-community
- */
- /*!40101 SET NAMES utf8 */;
- /*!40101 SET SQL_MODE=''*/;
- create database if not exists `test`;
- USE `test`;
- /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
- /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
- /*Table structure for table `friend` */
- DROP TABLE IF EXISTS `friend`;
- CREATE TABLE `friend` (
- `uid` bigint(20) NOT NULL,
- `fid` bigint(20) NOT NULL,
- PRIMARY KEY (`uid`,`fid`)
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
- /*Data for the table `friend` */
- insert into `friend`(`uid`,`fid`) values (1,2),(1,3),(1,4),(1,5),(1,6);
- /*Table structure for table `track` */
- DROP TABLE IF EXISTS `track`;
- CREATE TABLE `track` (
- `uid` bigint(20) NOT NULL,
- `trackid` bigint(20) NOT NULL,
- `inverse` bigint(20) DEFAULT NULL,
- PRIMARY KEY (`uid`,`trackid`)
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
- /*Data for the table `track` */
- insert into `track`(`uid`,`trackid`,`inverse`) values (2,1,-10),(2,2,-11),(2,3,-12),(3,1,-13),(3,4,-14),(3,6,-15),(4,1,-8),(5,6,-7);
- /*Table structure for table `user` */
- DROP TABLE IF EXISTS `user`;
- CREATE TABLE `user` (
- `uid` bigint(20) NOT NULL AUTO_INCREMENT,
- PRIMARY KEY (`uid`)
- ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
- /*Data for the table `user` */
- insert into `user`(`uid`) values (1),(2),(3),(4),(5),(6);
- /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
- /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
复制代码
查询语句如下:
select t.uid,t.trackid from user as u, friend as f, track as t where u.uid = f.uid and f.fid = t.uid order by t.inverse; |
explain结果如下:
-
- id select_type table type possible_keys key key_len ref rows Extra
- ------ ----------- ------ ------ ------------- ------- ------- ---------- ------ --------------------------------------------
- 1 SIMPLE f index PRIMARY PRIMARY 16 (NULL) 5 Using index; Using temporary; Using filesort
- 1 SIMPLE u eq_ref PRIMARY PRIMARY 8 test.f.uid 1 Using index
- 1 SIMPLE t ref PRIMARY PRIMARY 8 test.f.fid 1
复制代码
如何优化掉那个filesort?请指教 |
|