Sql多次返回行

时间:2014-09-09 15:33:50

标签: mysql sql database

我有以下sql:

select `items`.`id`, `items`.`item_url`, `items`.`title`, `items`.`description`, `items`.`item_image_name`, `items`.`downloads`, `items`.`likes`, `items`.`date` 
from `items` left join `categories` as `c` on `c`.`id` = `items`.`category_id` 
 left join `item_tags` as `it` on `it`.`item_id` = `items`.`id` 
 inner join `tags` as `t` on `t`.`id` = `it`.`tag_id` 
 where (`items`.`title` LIKE '%psd%' or `c`.`name` LIKE '%psd%' or `t`.`name` LIKE '%psd%') 
 order by `items`.`date` desc limit 12

但由于某种原因,某些行会从items表重复多次。有没有办法从项目中获取结果而不重复相同的项目ID。

3 个答案:

答案 0 :(得分:1)

如果您想避免重复数据,可以尝试使用 DISTINCT 。像这样:

select DISTINCT `items`.`id`, `items`.`item_url`, `items`.`title`, `items`.`description`, `items`.`item_image_name`, `items`.`downloads`, `items`.`likes`, `items`.`date` 
from `items` left join `categories` as `c` on `c`.`id` = `items`.`category_id` 
 left join `item_tags` as `it` on `it`.`item_id` = `items`.`id` 
 inner join `tags` as `t` on `t`.`id` = `it`.`tag_id` 
 where (`items`.`title` LIKE '%psd%' or `c`.`name` LIKE '%psd%' or `t`.`name` LIKE '%psd%') 
 order by `items`.`date` desc limit 12

或者您也可以使用 GROUP BY

select `items`.`id`, `items`.`item_url`, `items`.`title`, `items`.`description`, `items`.`item_image_name`, `items`.`downloads`, `items`.`likes`, `items`.`date` 
    from `items` left join `categories` as `c` on `c`.`id` = `items`.`category_id` 
     left join `item_tags` as `it` on `it`.`item_id` = `items`.`id` 
     inner join `tags` as `t` on `t`.`id` = `it`.`tag_id` 
     where (`items`.`title` LIKE '%psd%' or `c`.`name` LIKE '%psd%' or `t`.`name` LIKE '%psd%') 
     group by `items`.`id`, `items`.`item_url`, `items`.`title`, `items`.`description`, `items`.`item_image_name`, `items`.`downloads`, `items`.`likes`, `items`.`date` 
     order by `items`.`date` desc limit 12

答案 1 :(得分:0)

您需要在查询中使用DISTINCT关键字:

http://www.mysqltutorial.org/mysql-distinct.aspx

答案 2 :(得分:0)

您需要" GROUP BY items.id"