简体   繁体   中英

MySQL Distinct Inner Join

please excuse my lack of knowledge on this. I have limited experience with PHP and MySQL queries. I can do some basic queries, however, this is one I need to amend which is confusing me.

I have a query which pull all data for products that have awards assigned to them. However, if one product has multiple award, it shows that product multiple times. Ideally I want that product to be shown once.

I would look to apply a DISTINCT or UNIQUE value to the query, but the way the query is constructed, it doesn't appear to do anything.

The original query is the following:

<?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) { ?>

I have tried a few versions of changing the SELECT * for SELECT DISTINCT etc but no joy. Would anyone mid giving me a few pointers please?

If you * you select all the column so the distinct is unuseful

If you need a distinct result you should select explicitally only the column which you want the distinct value

Group by is for aggreagtion function and is not necessary  for distinct clause 

so, assuminng the column you need are col1, col2, and col3 only you should use a select like

    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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM