mysql distinct语句不起作用

时间:2012-05-13 10:53:07

标签: php mysql

  $query = "SELECT DISTINCT t.task_id, e.url,e.error_id, p.page_rank, e.scan_status, e.url_is_route,e.url_is_route,e.forbidden_word,e.google_host_fail,e.google_cache_fail,e.google_title_fail,e.robots_noindex_nofollow,e.xrobots_noindex_nofollow,e.title_fetch_warn,e.h1_fail,e.h2_fail,e.h3_fail,e.h1_warn,e.h2_warn,e.h3_warn 
              FROM `error_report` AS e 
              INNER JOIN task_pages AS t ON t.task_id=e.task_id
              INNER JOIN `pages` AS p ON p.page_id=t.page_id
              WHERE t.task_id=" . $this->task_id ;

我希望查询只能通过t.task_id区分。问题是,当我添加更多字段时...查询不再明显。还有一种方法可以通过t.task_id选择distinct吗?

2 个答案:

答案 0 :(得分:3)

而不是distinct使用group by

$query = "SELECT t.task_id, e.url,e.error_id, p.page_rank, e.scan_status, e.url_is_route,e.url_is_route,e.forbidden_word,e.google_host_fail,e.google_cache_fail,e.google_title_fail,e.robots_noindex_nofollow,e.xrobots_noindex_nofollow,e.title_fetch_warn,e.h1_fail,e.h2_fail,e.h3_fail,e.h1_warn,e.h2_warn,e.h3_warn 
          FROM `error_report` AS e 
          INNER JOIN task_pages AS t ON t.task_id=e.task_id
          INNER JOIN `pages` AS p ON p.page_id=t.page_id
          WHERE t.task_id=" . $this->task_id
          ."group by t.task_id";

答案 1 :(得分:1)

如果您添加更多字段,则应使用GROUP BY iirc。

请注意,您的额外字段应该是聚合的,例如MINMAX等.MySQL更宽容,并显示每个字段的第一个值(虽然不是很可靠)。