Alphabetically group all strings based on ID

Stuck on this ...
I need something like GROUP BY but also affects the grouping results for all other rows in the cat_name column respectively id (prod_id in the example). Example table:

 +------------------+--------+---------+-------------+--------------+
 | cat_name         | cat_id | prod_id | prod_name   | prod_img     |
 +------------------+--------+---------+-------------+--------------
 | Foo Category     |     54 |     755 | product a   | prod_a_img_1 |
 | A Category       |     22 |     755 | product a   | prod_a_img_3 |
 | Bar Category     |     59 |     755 | product a   | prod_a_img_2 |
 | Category three   |     85 |     767 | product b   | prod_b_img_1 |
 +------------------+--------+---------+-------------+--------------+

      

What I want to have:

+------------------+--------+---------+-------------+--------------+
| cat_name         | cat_id | prod_id | prod_name   | prod_img     |
+------------------+--------+---------+-------------+--------------
| A Category       |     54 |     755 | product a   | prod_a_img_1 |
| A Category       |     22 |     755 | product a   | prod_a_img_3 |
| A Category       |     59 |     755 | product a   | prod_a_img_2 |
| Category three   |     85 |     767 | product b   | prod_b_img_1 |
+------------------+--------+---------+-------------+--------------+

      

Categories have a unique ID, but I only need to select the first category in each row (in alphabetical order).

My complete request:

select categories.name as cat_name,
   categories.slug as cat_uri,
   categories.term_id as cat_id,
   object_id,
   term_taxonomy_id,
   ID as prod_id,
   post_title as prod_name,
   img as prod_img
   from
   wp_posts,
   wp_term_relationships,
   (select term_id,
   name,
   slug
   from
   wp_terms group by name) as categories
   where post_type = "product" and
   object_id = ID and
   term_taxonomy_id = term_id

      

+3


source to share


1 answer


I think you are looking at something like this:



SELECT (
        SELECT ti.cat_name 
        FROM yourTable ti 
        WHERE ti.prod_id = t.prod_id
        ORDER BY ti.cat_name
        LIMIT 1) As cat_name, 
    t.cat_id, 
    t.prod_id, 
    t.prod_name, 
    t.prod_img
FROM 
    yourTable t

      

+1


source







All Articles