使用不同的mysql问题

时间:2018-02-27 05:44:51

标签: mysql

我有一个查询

$getitreult = ("select distinct Project_Name,meetings.Start_date as Mdate,
    meeting_next.meetingDate as M1date, time
    from meetings left join meeting_next
        on meetings.m_id=meeting_next.fk_m_id
    where meetings.Start_date BETWEEN '27-Feb-2018' and '28-Feb-2018' or
          meetingDate BETWEEN '27-Feb-2018' and '28-Feb-2018' or
          meetings.Start_date='27-Feb-2018' or
          meetings.Start_date='28-Feb-2018' or
          meetingDate='27-Feb-2018' or
          meetingDate='28-Feb-2018'");

返回

   Project_Name | Mdate        | M1date       | time
   BAIF - Global| 21-Feb-2018  |  27-Feb-2018   11.30
   Manage       |  20-Feb-2018 |  27-Feb-2018  | 10.30
    Test        |  20-Feb-2018 |  28-feb-2018 | 10.00
   BAIF - Global| 27-Feb-2018  |  20-Feb-2018   11.30
   Manage       |  27-Feb-2018 |  06-march-2018  | 10.30

我需要不同的3个项目,但是由于这个日期它会返回两次。我怎么能解决这个问题?请帮帮我?预期输出

   Project_Name | Mdate        | M1date       | time
   BAIF - Global| 21-Feb-2018  |  27-Feb-2018   11.30
   Manage       |  20-Feb-2018 |  27-Feb-2018  | 10.30
    Test        |  20-Feb-2018 |  28-feb-2018 | 10.00

2 个答案:

答案 0 :(得分:2)

您可以尝试使用子查询来查找最早Mdate的每个项目的记录。下面的查询基本上与您在问题中发布的查询相同,但现在它包括对子查询的额外连接,以限制每个项目的最早开始日期。

SELECT
    Project_Name,
    Start_date AS Mdate,
    meetingDate AS M1date,
    time
FROM meetings m1
LEFT JOIN meeting_next m2
    ON m1.m_id = m2.fk_m_id
INNER JOIN
(
    SELECT Project_Name, MIN(Start_date) AS min_start_date
    FROM meetings
    GROUP BY Project_Name
) t
    ON m1.Project_Name = t.Project_Name AND
       m1.Start_date   = t.min_start_date
WHERE
    m1.Start_date BETWEEN '27-Feb-2018' AND '28-Feb-2018' OR
    m2.meetingDate BETWEEN '27-Feb-2018' AND '28-Feb-2018' OR
    m1.Start_date IN ('27-Feb-2018', '28-Feb-2018') OR
    m2.meetingDate IN ('27-Feb-2018', '28-Feb-2018');

请注意,我质疑您的日期文字,例如27-Feb-2018。如果它确实有效,则意味着您将日期存储为文本,这是不可取的。如果,则使用ISO兼容的日期文字,例如2018-02-27代替27-Feb-2018

此外,不是按项目名称聚合,而是使用某种描述每个项目的唯一ID更好。这将消除两个项目发生同名的问题。

答案 1 :(得分:0)

看看是否有效

("select Project_Name,meetings.Start_date as Mdate,
    meeting_next.meetingDate as M1date, time
    from meetings left join meeting_next
        on meetings.m_id=meeting_next.fk_m_id
    group by Project_Name
    having meetings.Start_date BETWEEN '27-Feb-2018' and '28-Feb-2018' or
          meetingDate BETWEEN '27-Feb-2018' and '28-Feb-2018' or
          meetings.Start_date='27-Feb-2018' or
          meetings.Start_date='28-Feb-2018' or
          meetingDate='27-Feb-2018' or
          meetingDate='28-Feb-2018'");