从第二个表JOIN中选择最大时间

时间:2016-10-18 10:05:10

标签: mysql sql

SELECT q.uid, q.title, q.category_id, CONCAT(CONCAT(q.text,'\n'),a.answer) as description
FROM questions q
LEFT JOIN (
     SELECT question_id, crdate, GROUP_CONCAT(text SEPARATOR '|| ') answer
     FROM answers
     GROUP BY question_id
     ORDER BY crdate DESC
) a ON q.uid = a.question_id
WHERE q.deleted = 0 AND q.answers > 0 

我想从第一个表格中选择uid,title和category id,从第二个表格中选择所有文本和 MAX crdate。此查询选择Min crdate。我该如何改变呢?

UPD 我有桌子问题和答案。作为表格的名称,我选择问题和答案。一个问题可能有几个答案。我希望在一个变量中连接所有答案(稍后将一些变量连接在一起用于全文搜索)并选择最后一个答案的crdate。

2 个答案:

答案 0 :(得分:1)

试试这个

SELECT q.uid, q.title, q.category_id, CONCAT(CONCAT(q.text,'\n'),a.answer) as description
FROM questions q
LEFT JOIN (
     SELECT question_id, max(crdate) as crdate, GROUP_CONCAT(text SEPARATOR '|| ') answer
     FROM answers
     GROUP BY question_id
     ORDER BY crdate DESC
) a ON q.uid = a.question_id
WHERE q.deleted = 0 AND q.answers > 0 
GROUP BY q.uid

答案 1 :(得分:1)

使用两个连接:

SELECT q.uid, q.title, q.category_id, CONCAT(CONCAT(q.text,'\n'),a.answer) as description
FROM questions q LEFT JOIN 
     (SELECT a.question_id, a.crdate, GROUP_CONCAT(a.text SEPARATOR '|| ') answer
      FROM answers a JOIN
           (SELECT a2.question_id, MAX(a2.crdate) as maxcr
            FROM answers a2
            GROUP BY a2.question_id
           ) a2
           ON a2.question_id = a.question_id and a2.maxcr = a.crdate
      GROUP BY question_id
     ) a
     ON q.uid = a.question_id
WHERE q.deleted = 0 AND q.answers > 0 
GROUP BY q.uid;

最里面的子查询获取问题答案的最大创建日期。中间子查询做你想要的,将答案连接在一起。

目前还不清楚外部GROUP BY正在做什么。真的有必要吗?为什么使用没有聚合函数的GROUP BY?外部SELECT中的其他其他列应使用哪些值?您的问题没有提供足够的信息来解决这些问题,但即使在获得最新的crdate答案后,查询仍然看起来仍然可疑。