对mysql中的表连接应用限制

时间:2015-09-04 06:42:07

标签: php mysql

我有两个表用户和查询。用户可以发布多个查询。

MySQL表架构: -

CREATE TABLE `users` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `email` varchar(100) NOT NULL,
  `password` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

CREATE TABLE `queries` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `address` text,
  `city` varchar(100) NOT NULL,
  `state` varchar(100) NOT NULL,
  `zipcode` int(11) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

我想对查询从每个用户的查询表中获取5个查询应用限制。

我应该如何为此编写查询?

1 个答案:

答案 0 :(得分:2)

试一试 -

SELECT x.*
FROM (SELECT t.user_id,t.id,
               CASE 
                 WHEN @category != t.user_id THEN @rownum := 1 
                 ELSE @rownum := @rownum + 1 
               END AS rank,
               @category := t.user_id AS var_category
          FROM queries t
          JOIN (SELECT @rownum := NULL, @category := '') r     
      ORDER BY t.user_id,t.id) X
      WHERE x.rank<=5