感谢您的精力充沛。
我有两种表用于某种社交网络,表A用于内容,表B用于喜欢:
表A:
CREATE TABLE `A` (
`id` int(10) unsigned NOT NULL,
`id_user` int(10) unsigned NOT NULL,
`title` varchar(255) DEFAULT NULL,
`path` text,
`ext` varchar(15) DEFAULT NULL,
`image_type` varchar(100) DEFAULT NULL,
`link_url` text,
`creation_date` datetime DEFAULT NULL,
`size` float DEFAULT NULL,
`type` int(10) unsigned DEFAULT NULL,
`number_share` int(10) unsigned NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `A`
ADD PRIMARY KEY (`id`), ADD KEY `id_user` (`id_user`);
表B:
CREATE TABLE B (
`id_b` int(10) unsigned NOT NULL,
`id_user` int(10) unsigned NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `B`
ADD PRIMARY KEY (`id_b`,`id_user`), ADD KEY `id_user` (`id_user`);
我想用这个命令从mysql记录中检索:
1st most popular
1st most recent
2nd most popular
2nd most recent
.....
任何人都可以告诉我如何通过mysql(如果可能)或易于使用的东西组合这个不是2个不同的查询吗?
编辑1:
如果我有这种情况:
首选(流行)的结果: ID 3 五 12 4 65 2
和
第二次选择(最近)的结果:
id
100
121
3
我将打印我的元素宽度id:
id
3
100
5
121
12
我希望第二个查询中的id = 3不被考虑,因为已经发布了
谢谢!
答案 0 :(得分:1)
<强>计划强>
- 使用变量,按顺序排列人气
- 使用变量,并按排序最近排名
- union all
- 由rnk,cat
重新订购- 按ID分组以限制为第一个ID
输入[样本]
+----+---------+--------+--------+--------+------------+----------+--------------------------+--------+--------+--------------+
| id | id_user | title | path | ext | image_type | link_url | creation_date | size | type | number_share |
+----+---------+--------+--------+--------+------------+----------+--------------------------+--------+--------+--------------+
| 1 | 22 | (null) | (null) | (null) | (null) | (null) | August, 09 2015 10:54:57 | (null) | (null) | 0 |
| 2 | 33 | (null) | (null) | (null) | (null) | (null) | August, 09 2015 07:54:57 | (null) | (null) | 0 |
| 3 | 44 | (null) | (null) | (null) | (null) | (null) | August, 09 2015 08:54:57 | (null) | (null) | 0 |
+----+---------+--------+--------+--------+------------+----------+--------------------------+--------+--------+--------------+
+------+---------+
| id_b | id_user |
+------+---------+
| 3 | 8 |
| 3 | 9 |
| 3 | 21 |
| 3 | 22 |
| 1 | 55 |
| 3 | 55 |
| 1 | 66 |
| 1 | 77 |
+------+---------+
<强>查询强>
set @rnk_pop := 0;
set @rnk_rec := 0;
-- popularity ranking
select cat, id, rnk
from
(
select cat, id, rnk
from
(
select cat, id, occurs, @rnk_pop := @rnk_pop + 1 as rnk
from
(
select 'popularity' as cat, A.id, count(B.id_b) as occurs
from A
left join B
on B.id_b = A.id
group by A.id
order by occurs desc
) q1
) pop_sort
union all
-- recent ranking
select cat, id, rnk
from
(
select 'recent' as cat, id, @rnk_rec := @rnk_rec + 1 as rnk
from A
order by creation_date desc
) rec_sort
order by rnk, cat
) all_q
group by id
order by rnk, cat
;
<强>输出强>
+------------+----+-----+
| cat | id | rnk |
+------------+----+-----+
| popularity | 3 | 1 |
| recent | 1 | 1 |
| popularity | 2 | 3 |
+------------+----+-----+
备注强>
上面的排名输出将用于加入以显示对内容有用的任何信息..