phpmyadmin命令(喜欢在x时间内完成,不喜欢在x时间内完成)

时间:2017-06-14 14:26:19

标签: mysql sql

我想知道是否有办法创建一个sql命令,可以在一段时间内完成排序(喜欢减去不喜欢)。下面的例子展示了当我只喜欢(它有效)时我是如何做到这一点的,但是当考虑到不喜欢它时,它对我来说变得复杂。

SELECT count(likes.lid) as 'amount', posts.* FROM likes 
join posts on posts.pid = likes.pid
WHERE likes.DateLiked >= DATE_ADD(CURRENT_DATE, INTERVAL -3 DAY)
group by likes.pid order by amount  DESC;

我目前有三张桌子:

CREATE TABLE posts (
    pid int(11) AUTO_INCREMENT PRIMARY KEY,
    uid int(11) not null,
    Content text not null,
    Category varchar(100) not null,
    Subject varchar(100) not null,
    DatePublished datetime not null,
    TypeData VARCHAR(100) NOT NULL DEFAULT 'none',
    Data VARCHAR(500) NOT NULL
);

CREATE TABLE likes (
    lid int(12) AUTO_INCREMENT PRIMARY KEY,
    uid int(11) NOT NULL,
    Username varchar(200) NOT NULL,
    pid int(11) NOT NULL,
    DateLiked DateTime NOT NULL,
    ipConnect varchar(200) NOT NULL

)

CREATE TABLE dislikes (
    lid int(12) AUTO_INCREMENT PRIMARY KEY,
    uid int(11) NOT NULL,
    Username varchar(200) NOT NULL,
    pid int(11) NOT NULL,
    DateLiked DateTime NOT NULL,
    ipConnect varchar(200) NOT NULL
);

我正在寻找一个可以在一定时间内按最高评级(喜欢 - 不喜欢)订购帖子的命令(即,如果某人喜欢2天前它很重要,但一年前并不算数)。

感谢所有帮助, 祝你有个美好的一天。

1 个答案:

答案 0 :(得分:0)

首先聚合,然后加入:

select
  coalesce(l.cnt, 0) - coalesce(dl.cnt, 0) as likes,
  p.*
from posts p
left join
(
  select pid, count(*) as cnt
  from likes
  where dateliked >= date_add(current_date, interval -3 day)
  group by pid
) l on l.pid = p.pid
left join
(
  select pid, count(*) as cnt
  from dislikes
  where dateliked >= date_add(current_date, interval -3 day)
  group by pid
) dl on dl.pid = p.pid
order by coalesce(l.cnt, 0) - coalesce(dl.cnt, 0) desc;