Mysql与4个表中的最新更新连接

时间:2014-05-09 07:36:56

标签: php mysql sql join

嗨,这是我的桌子..

表格网站

     sid  sname       uid
    ----  ----------  ----
       1  aaa.com      1
       5  bbb.com      1 

表keywords_s

     kid  skeywoird       
    ----  ----------  
       1  word1    
       2  word2

表匹配

mid    uid    sid     kid       
----  ------  -----  -----
   1    1        1     1      
   2    1        1     2    

表等级

 mid   rank    dateon           url       
----  ------   -------         -----
   2     7    08-May-2014      bbb.com/a
   2     6    09-May-2014      bbb.com/2  

我的查询

"SELECT 
    keywords_s.skeyword,
    keywords_s.kid,
    sites.sname,
    rank.rank,
    rank.url,
    rank.dateon
    FROM matchon
    Inner JOIN sites ON sites.sid = matchon.sid
    Inner JOIN keywords_s ON keywords_s.kid = matchon.kid
    Inner JOIN rank ON rank.mid = matchon.mid
    where matchon.uid = :uid and sites.sname = :sname and sites.deactive != '1'
    group by keywords_s.skeyword order by rank.rank
    "

我正在获得输出

rank   keyword    dateon        url       
----  ---------   -------      -----
   7   word2    08-May-2014    bbb.com/a

所需的输出是

rank   keyword    dateon        url       
----  ---------   -------      -----
   6   word2    09-May-2014    bbb.com/2

这是我想要的......

第一组由keywords_s.skeyword按排名顺序排列(这是即将发布但是)

rank.slno desc(不工作)的第二顺序

(我需要第二个订单才能工作,所以我可以获得最新的排名和日期,按skeyword分组,按排名排序)

2 个答案:

答案 0 :(得分:1)

SELECT keywords_s.skeywor
     , keywords_s.kid
     , sites.sname
     , rank.rank
     , rank.url
     , rank.dateon
FROM matchon JOIN sites ON sites.sid = matchon.sid
             JOIN keywords_s ON keywords_s.kid = matchon.kid
             JOIN rank ON rank.mid = matchon.mid AND
                          rank.dateon = (SELECT MAX(dateon) FROM rank WHERE mid =  matchon.mid)
WHERE matchon.uid = :uid and sites.sname = :sname and sites.deactive != '1'
GROUP BY keywords_s.skeyword order by rank.rank

答案 1 :(得分:0)

这应该按照您的要求运作

  

"Select * from(SELECT keywords_s.skeyword, keywords_s.kid, sites.sname, rank.rank, rank.url, rank.dateon FROM matchon Inner JOIN sites ON sites.sid = matchon.sid Inner JOIN keywords_s ON keywords_s.kid = matchon.kid Inner JOIN rank ON rank.mid = matchon.mid where matchon.uid = :uid and sites.sname = :sname and sites.deactive != '1' order by rank.rank desc)xyz group by xyz.skeyword "