通过mysql与group联合

时间:2017-09-20 12:39:04

标签: mysql group-by union

您好我有一个查询如下,但分组不起作用。

SELECT messages.thread_id,messages.subject,messages.message_id,messages.status,messages.attachment,login.name, DATE_FORMAT( messages.date, '%D-%b-%Y' ) as date from messages inner join login on messages.receiver = login.id where (messages.sender = '" . mysql_real_escape_string(trim($_SESSION['login_id'])) . "' and messages.status = 'trash' ) 
UNION SELECT messages.thread_id,messages.subject,messages.message_id,messages.status,messages.attachment,login.name, DATE_FORMAT( messages.date, '%D-%b-%Y' ) as date from messages inner join login on messages.sender = login.id where (messages.receiver = '" . mysql_real_escape_string(trim($_SESSION['login_id'])) . "' and messages.status = 'trash')  GROUP BY messages.thread_id 

2 个答案:

答案 0 :(得分:0)

你必须在union select周围加上括号,给它一个别名并从中选择:

SELECT A.* FROM
(messages.thread_id,messages.subject,messages.message_id,messages.status,mess
ages.attachment,login.name, DATE_FORMAT( messages.date, '%D-%b-%Y' ) as 
date from messages inner join login on messages.receiver = login.id 
where (messages.sender = '" . 
mysql_real_escape_string(trim($_SESSION['login_id'])) . "' and 
messages.status = 'trash' ) 
UNION SELECT 
messages.thread_id,messages.subject,messages.message_id,messages.status,messa
ges.attachment,login.name, DATE_FORMAT( messages.date, '%D-%b-%Y' ) as 
date from messages inner join login on messages.sender = login.id where 
(messages.receiver = '" . 
mysql_real_escape_string(trim($_SESSION['login_id'])) . "' and 
messages.status = 'trash')) AS A 
GROUP BY A.thread_id

答案 1 :(得分:0)

将查询包装到外部查询,以便它可以对来自两个查询的组合结果进行分组。

SELECT z.*
FROM
(
    SELECT messages.thread_id, messages.subject, messages.message_id, messages.status,
    messages.attachment, login.name, DATE_FORMAT( messages.date, '%D-%b-%Y' ) as date
    FROM messages
    INNER JOIN login ON messages.receiver = login.id
    WHERE messages.sender = '" . mysql_real_escape_string(trim($_SESSION['login_id'])) . "'
    AND messages.status = 'trash' 
    UNION
    SELECT messages.thread_id, messages.subject, messages.message_id, messages.status,
    messages.attachment, login.name, DATE_FORMAT( messages.date, '%D-%b-%Y' ) as date
    FROM messages
    INNER JOIN login ON messages.sender = login.id
    WHERE messages.receiver = '" . mysql_real_escape_string(trim($_SESSION['login_id'])) . "'
    AND messages.status = 'trash'
) AS z
GROUP BY z.thread_id