请原谅我对此缺乏了解。我对PHP和MySQL查询的经验有限。我可以做一些基本的查询,但是,这是我需要修改的,这让我感到困惑。
我有一个查询,它会为已分配奖励的产品提取所有数据。但是,如果一个产品有多个奖项,则会多次显示该产品。理想情况下,我希望该产品能够展示一次。
我希望将DISTINCT或UNIQUE值应用于查询,但是构造查询的方式,它似乎没有做任何事情。
原始查询如下:
<?php
$get_awards = $wpdb->get_results("
SELECT *
FROM wp_posts
WHERE post_type = 'award'
AND post_status = 'publish'
AND YEAR(CAST(post_date AS DATE))=2009
GROUP
BY post_title
ORDER
BY post_date DESC
");
foreach ($get_awards as $award) {
$get_products = $wpdb->get_results("SELECT * FROM wp_posts INNER JOIN wp_postmeta ON wp_posts.ID = wp_postmeta.post_id WHERE post_type = 'ice-cream' AND post_status = 'publish' AND meta_key = 'awards' AND meta_value LIKE '%''".$award->ID."''%' OR post_type = 'frozen-yoghurt' AND post_status = 'publish' AND meta_key = 'awards' AND meta_value LIKE '%''".$award->ID."''%' OR post_type = 'sorbet' AND post_status = 'publish' AND meta_key = 'awards' AND meta_value LIKE '%''".$award->ID."''%'");
foreach ($get_products as $product) { ?>
我尝试了几个版本的SELECT * for SELECT DISTINCT等,但没有快乐。请问中间有人指点我吗?
答案 0 :(得分:0)
如果你*选择了所有列,那么distinct是无用的
如果您需要不同的结果,则应明确选择您想要不同值的列
Group by is for aggreagtion function and is not necessary for distinct clause
所以,你需要的列是col1,col2和col3,你应该使用像
这样的选择 SELECT DISTINCT col1, col2, col2
FROM wp_posts
WHERE post_type = 'award'
AND post_status = 'publish'
AND YEAR(CAST(post_date AS DATE))=2009
GROUP BY post_title
ORDER BY post_date DESC