MySQL UNION在同一个表上有两个WHERE子句

时间:2017-08-31 08:54:05

标签: mysql union

我有一张表alerts

date | alert | status | sentDate | id 

在此表格中,在我发送提醒后,我将状态设置为“sent”并设置发送日期。默认状态为“not”(这意味着尚未发送)。

现在,我想获取最后发送的日期,我可以使用以下查询获取此信息

SELECT sentDate FROM alerts WHERE id = someid AND status = 'sent' Order by date desc limit 1;

另外,我想获取尚未发送的最新警报,我正在使用此查询

SELECT date, alert FROM alerts WHERE id = someid AND status = 'not' order by date asc limit 1;

是否可以在一个查询中执行此操作?也许使用UNION。我试图在这两个查询上应用UNION / UNION ALL,但它给了我错误。

有人可以帮忙吗?

提前致谢。

4 个答案:

答案 0 :(得分:1)

SELECT 
max(CASE WHEN status = 'sent' THEN DATE END) AS sentDate,
max(CASE WHEN status = 'not' THEN DATE END) AS notSentDate 
FROM alerts WHERE id = someid 

您可以尝试以上查询。

它会帮助你。

答案 1 :(得分:1)

你可以试试这个:

SELECT MAX(t.sentDate) AS sentDate, MAX(t.date) AS date, MAX(alert) AS alert
FROM
(
    SELECT MAX(sentDate) AS  sentDate, "" AS date, "" AS alert
    FROM alerts 
    WHERE id = someid 
    AND status = 'sent'

    UNION 

    SELECT "" AS sentDate, date, alert 
    FROM alerts 
    WHERE id = someid 
    AND status = 'not'
) t

答案 2 :(得分:0)

你可以尝试这个

    SELECT 
    (Select date from alerts where id= someid AND status='not' 
ORDER by date DESC limit 1) latestNotSentDate, 
    (Select date from alerts where id= someid AND status='sent' 
ORDER BY date DESC limit 1) latestSentDate;

答案 3 :(得分:-1)

查询中的列数必须相同,请尝试以下方法:

SELECT sentDate,'' FROM alerts WHERE id = 'id' AND status = 'sent' Order by date desc limit 1;

UNION

SELECT date, alert FROM alerts WHERE id = 'id' AND status = 'not' order by date asc limit 1;

此外,我认为状态无关紧要,这些信息是由sentDate的存在提供的。

我想你可以写:

SELECT sentDate,'' FROM alerts WHERE id = 'id' AND sentDate is not null Order by date desc limit 1;

    UNION

    SELECT date, alert FROM alerts WHERE id = 'id' AND sentDate is NULL order by date asc limit 1;