找到两列中重复的mySQL结果 - GROUP BY不起作用

时间:2017-01-20 01:16:28

标签: mysql group-by duplicates

我有一个事件列表,我想找到即将发生的事件的重复项。由于同一事件可以有几个不同的事件标题,我认为这里最安全的赌注是查找同一天在同一场所发生的事件,并从那里手动删除重复。

Similar question was asked here.

$todays_date = date('Y-m-d');   
$sql="         
SELECT place_name, event_title, start_date, count(*)
FROM main WHERE start_date  >= '$todays_date'
GROUP BY start_date, place_name HAVING count(*) > 1";
    $result = mysql_query($sql);
    //display events
    while ($row = mysql_fetch_array($result)) 
        {
            echo $row['place_name'] . "- ";
            echo $row['event_title'] . "- "; 
            echo $row['start_date'] . "<br/>"; 
        }

这根本没有给我一个预期的结果,事实上,我不知道这个记录集是如何组装的。

地点 - 活动名称 - 日期

Rotary Centre for the Arts- Leela Gilday - 2017-03-10
Rotary Centre for the Arts- Joe Trio - 2017-03-21
Vernon and District Performing Arts Center- Shay Keubler's GLORY- 2017-04-01
Vernon and District Performing Arts Center- A Midsummer Night's Dream- 2017-04-30
Vernon and District Performing Arts Centre- Canadiana Suite - 2017-05-06
Kelowna Community Theatre - Glenn Miller Orchestra- 2017-06-27

非常感谢任何提示。

我在没有日期的情况下尝试了它,只是通过event_title和place_name进行分组,并使用类似的奇怪输出,其中唯一的重复是场地名称(place_name)的重复。

2 个答案:

答案 0 :(得分:1)

使用GROUP BY时,每组只能获得一行。您选择的其他列将从组中随机选择。

如果要查看重复组中的所有行,请使用查找重复项的查询将表连接起来。

SELECT t1.*
FROM main AS t1
JOIN (SELECT place_name, start_date
      FROM main 
      WHERE start_date  >= '$todays_date'
      GROUP BY start_date, place_name 
      HAVING count(*) > 1) AS t2
ON t1.place_name = t2.place_name AND t1.start_date = t2.start_date

答案 1 :(得分:0)

试试这个:

select main_count,a.place_name,b.event_title, b.start_date from
(select count(1)as main_count, place_name from main WHERE start_date  >= '".$todays_date."' group by place_name having count(1) >1) as a

left join

(select  place_name, event_title, start_date from main) as b
on a.place_name = b.place_name