QUERY:
mysql> SELECT DISTINCT (stories.id), stories.news_type, story_keywords.keyword
FROM (`stories`) LEFT JOIN `story_keywords` ON `stories`.`id`
=`story_keywords`.`story_id`
WHERE `image_full_url` != '' AND `order` != 0
AND `news_type` IN ('movie_review', 'movie')
AND `keyword` IN ('topnews', 'toptablet')
ORDER BY `created` DESC, `order` DESC LIMIT 5;
结果:(注意ID不明显)
+--------+--------------+-----------+
| id | news_type | keyword |
+--------+--------------+-----------+
| 100895 | movie_review | topnews |
| 100895 | movie_review | toptablet |
| 100798 | movie_review | toptablet |
| 100060 | movie_review | toptablet |
| 100060 | movie_review | topnews |
+--------+--------------+-----------+
5 rows in set (0.00 sec)
答案 0 :(得分:4)
select distinct
适用于正在提取的行,而不适用于该行中的单个字段。结果集中的每一行 IS 不同。
答案 1 :(得分:0)
DISTINCT
已应用于整行,因为keyword
列对于与DISTINCT
条件匹配的不同行有多个值。如果要返回一行,则需要确定返回keyword
的值。
如果要将值连在一起,则可以使用GROUP_CONCAT()
:
SELECT stories.id, stories.news_type, GROUP_CONCAT(story_keywords.keyword)
FROM (`stories`)
LEFT JOIN `story_keywords`
ON `stories`.`id`=`story_keywords`.`story_id`
WHERE `image_full_url` != '' AND `order` != 0
AND `news_type` IN ('movie_review', 'movie')
AND `keyword` IN ('topnews', 'toptablet')
GROUP BY stories.id, stories.news_type
ORDER BY `created` DESC, `order` DESC LIMIT 5;
数据会像这样返回:
| id | news_type | keyword |
+--------+--------------+---------------------+
| 100895 | movie_review | topnews,toptablet |
| 100798 | movie_review | toptablet |
| 100060 | movie_review | toptablet, topnews |
答案 2 :(得分:0)
DISTINCT选项删除重复的记录,而不是字段值。 如果要选择不同的ID,则可以使用此查询 -
SELECT
stories.id,
GROUP_CONCAT(stories.news_type),
GROUP_CONCAT(story_keywords.keyword)
FROM (`stories`)
LEFT JOIN `story_keywords`
ON `stories`.`id` = `story_keywords`.`story_id`
WHERE
`image_full_url` != ''
AND `order` != 0
AND `news_type` IN ('movie_review', 'movie')
AND `keyword` IN ('topnews', 'toptablet')
GROUP BY
stories.id
ORDER BY
`created` DESC
, `order` DESC
LIMIT
5;