连接具有父ID的表

时间:2013-07-04 21:14:37

标签: mysql types parent-child

我需要一些关于mysql的建议,假设我们有3个表:

deletionlog:

此表显示所有软删除的帖子和帖子以及删除时间的日期:

primaryid   type      dateline
       12   thread    1372789192
       13   thread    1372860700
       15   thread    1372798567
       16   thread    1372818402
       17   thread    1372931230
       37   post      1372790038
       43   post      1372798587

主题:

此表显示所有线程及其fourmid:

threadid   forumid  
      12         2
      13         2
      14         2
      15         4
      16         2
      17         2 

后:

此表显示所有帖子及其主题:

    postid  threadid  
    35        12
    36        13
    37        13
    38        13
    39        12
    40        12
    41        14
    42        14
    43        14
    44        15
    45        16
    46        17

我想要的是显示删除的线程的最后日期和删除的帖子连接与其他表信息,如forumid:

primaryid   type     forumid    dateline
       17   thread         2    1372931230
       43   post           2    1372931230

好的,我设法获得了这样的帖子和帖子的最后删除日期:

SELECT        *
FROM          deletionlog AS a
INNER JOIN     
(
    SELECT    type, Max(dateline) AS dateline
    FROM      deletionlog
    GROUP BY  type
) AS b
ON            a.type = b.type
AND           a.dateline = b.dateline
WHERE b.type in('thread','post')";

但是这个只有一个表我想加入表格帖子和帖子来提取fourmid所以有什么建议吗?

1 个答案:

答案 0 :(得分:1)

不幸的是,您提供的数据库结构甚至不符合第二种普通形式。所以,我不得不使用UNION编写这个丑陋的请求:

SELECT
    deletionlog.primaryid,
    deletionlog.type,
    thread.forumid,
    deletionlog.dateline
FROM
    deletionlog
INNER JOIN
    thread
ON
    deletionlog.primaryid=thread.threadid
WHERE
    deletionlog.type='thread'
GROUP BY
    deletionlog.type
HAVING
    MAX(deletionlog.dateline)

UNION

SELECT
    deletionlog.primaryid,
    deletionlog.type,
    thread.forumid,
    deletionlog.dateline
FROM
    deletionlog
INNER JOIN
    post
ON
    deletionlog.primaryid=post.postid
INNER JOIN
    thread
ON
    post.threadid=thread.threadid
WHERE
    deletionlog.type='post'
GROUP BY
    deletionlog.type
HAVING
    MAX(deletionlog.dateline)