473,803 Members | 3,167 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Group_concat()

bilibytes
128 New Member
Hi,

I'm wondering how to achieve the following:

well i don't know if you guys like wine but I have to explain a very little on wine to explain my example: Wine is made from grape and a wine bottle may be made from different sorts of grape. So when you have a bottle it usually says: 10% of shyra, 50% of cabernet and 40% of merlot
meaning that the wine in the bottle was made from that percent of each grape type.

that was it for wine.

now SQL

need to store all the grapes that a wine has and their respective percentage.
so i have my bottles which are stored under a table called Wine
then i have all existing types of grapes stored in Grape
and i associate these two things by a third table called WineToGrape
its a one to many relationship.
here are the tables examples:

Expand|Select|Wrap|Line Numbers
  1. Wine
  2. wine_id | name
  3.  
  4. Grape
  5. grape_id | name
  6.  
  7. WineToGrape
  8. wtg_id | grape_id | wine_id | percentage
  9.  
Now the fun part: How do i retrieve a list of all the wines with all their respective grapes and percentage?

I see one option which implies PHP or any other language:
Expand|Select|Wrap|Line Numbers
  1. SELECT 
  2.     w.wine_id AS wineId, 
  3.     w.name AS wineName,
  4.     g.grape_id AS grapeId, 
  5.     g.name AS grapeName, 
  6.     wtg.percentage AS grapePercentageInWine 
  7. FROM 
  8.     WineToGrape AS wtg
  9.         INNER JOIN Wine AS w ON (wtg.wine_id = w.wine_id) 
  10.         INNER JOIN Grape AS g ON (wtg.grape_id = g.grape_id);
  11.  
Then i would end up with a big array that would have many duplicate wine_id's and i can't do a GROUP BY because it would get off the grapes and i want all the grapes
So from PHP i would have to loop through all the rows and if the wine_id in the row already exists then i would append the grape to the wine_id key like this:
Expand|Select|Wrap|Line Numbers
  1. $wines = array();
  2. while($row = mysql_fetch_array($resultset)){
  3.     //if the wine name was not already stored, store it
  4.     if (! isset($wines[$row['wineId']])) {
  5.         $wines[$row['wineId']]['name'] = $row['wineName'];
  6.     }
  7.     //any time there is a new record it the grape name and percetage has
  8.     //to be added to the wine element in the array
  9.         $wines[$row['wineId']]['grapes'][$row['grapeId']]['name'] = $row['grapeName'];
  10.         $wines[$row['wineId']]['grapes'][$row['grapeId']]['percentage'] = $row['grapePercentageInWine'];
  11.     }
  12. }
So an example result array would be:

Expand|Select|Wrap|Line Numbers
  1. array(3=>array('name'=>'wine3',
  2.                   'grapes'=> array(26=>array('name'=>'grape26',
  3.                                             'percentage'=>40),
  4.                                   34=>array('name'=>'grape26',
  5.                                             'percentage'=>60)
  6.                                  )
  7.                   ),
  8.      7=>array('name'=>'wine7',
  9.               'grapes'=> array(31=>array('name'=>'grape31',
  10.                                          'percentage'=>15),
  11.                               34=>array('name'=>'grape34',
  12.                                          'percentage'=>40),
  13.                               15=>array('name'=>'grape15',
  14.                                          'percentage'=>45)
  15.                              )
  16.  
  17.               ),
  18.      23=>array('name'=>'wine23',
  19.               'grapes'=> array(31=>array('name'=>'grape31',
  20.                                          'percentage'=>100),
  21.                              )
  22.               )
  23. );
Once i have my $wines array i would have to loop again through all the elements and nodes in the array to display them.

That is feasable but i have heard of another possibility:
GROUP_CONCAT() sql function

group concat would give me a concatenated string of all the grapes with this sql:

Expand|Select|Wrap|Line Numbers
  1. SELECT 
  2.     w.wine_id AS wineId, 
  3.     w.name AS wineName,
  4.     GROUP_CONCAT(g.grape_id) AS grapeId, 
  5.     g.name AS grapeName, 
  6.     wtg.percentage AS grapePercentageInWine 
  7. FROM 
  8.     WineToGrape AS wtg
  9.         INNER JOIN Wine AS w ON (wtg.wine_id = w.wine_id) 
  10.         INNER JOIN Grape AS g ON (wtg.grape_id = g.grape_id);
  11.  
But what i would not have my percentages, so that's where i need help:

I need to know how to use the GROUP_CONCAT() function to concatenate all the grapes and percentages like this: 'grape23 10%, grape11 90%' for each wine.

is that feasible ?

Thank you just for the fact of having read so far!

regards

bilibytes
Aug 18 '09 #1
1 5753
labmonkey111
44 New Member
In GROUP_CONCAT() you can put any expression you want, so you should be able to do something like this:

Expand|Select|Wrap|Line Numbers
  1. SELECT 
  2.     w.wine_id AS wineId, 
  3.     w.name AS wineName,
  4.     GROUP_CONCAT(CONCAT(g.name,' ',wtg.percentage)) AS grapeId
  5. FROM 
  6.     WineToGrape AS wtg
  7.         INNER JOIN Wine AS w ON (wtg.wine_id = w.wine_id) 
  8.         INNER JOIN Grape AS g ON (wtg.grape_id = g.grape_id);
  9.  
I think that will do what you need it to.
Aug 19 '09 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

1
2715
by: peter stickney | last post by:
I am using the GROUP_CONCAT() as follows: SELECT (SELECT CONCAT(ProjectName) FROM Project WHERE FIND_IN_SET(ProjectID, RelatedProjectID))AS RelatedProject We have a project tracker system and we can have one project be related to several different projects. the issue is when there is only 1 related project associated with another project, this query does not work. Is there some sort of bug with GROUP_CONCAT?
2
1709
by: phillip.s.powell | last post by:
Here are my results using MySQL 4.1.12 and I honestly don't think this is right, but can't figure out what to do: mysql> select id, group_concat(DISTINCT school_enrollment_time_name SEPARATOR ',') as school_enrollment_time_display from school_enrollment_time group by id; +----+--------------------------------+ | id | school_enrollment_time_display | +----+--------------------------------+ | 1 | spring |
2
1945
by: phillip.s.powell | last post by:
SELECT s.id, s.student_first_name, s.student_last_name, IF(s.student_ethnicity_interest_other IS NOT NULL AND s.student_ethnicity_interest_other != '', CONCAT(s.student_ethnicity_interest_other, ', ', e.ethnicity_name), GROUP_CONCAT(DISTINCT e.ethnicity_name ORDER BY upper(e.ethnicity_name)) ) AS ethnicity_name FROM student s, ethnicity e, student_ethnicity_interest_assoc seia
0
1228
by: phillip.s.powell | last post by:
$if1 = "IF(s.student_ethnicity_interest_other IS NOT NULL AND s.student_ethnicity_interest_other != '', " . " CONCAT(s.student_ethnicity_interest_other, ', ', GROUP_CONCAT(e.ethnicity_name ORDER BY upper(e.ethnicity_name))), " . ' GROUP_CONCAT(e.ethnicity_name ORDER BY upper(e.ethnicity_name))' . " ) AS ethnicity_name \n\n"; This segment of a larger SQL query produces a string that normally looks like these:
0
3325
by: gmorris | last post by:
I am attempting to pull data from multiple tables into a resultset that I can use as an Excel spreadsheet for reporting. Here is my query so far: SELECT b.bug_id,p.realname as 'Assigned' ,bug_status,b.resolution,b.short_desc,l.thetext as 'Description/Comments',b.creation_ts as 'Opened',b.delta_ts as 'Last Update' FROM bugs b, longdescs l, profiles p WHERE b.bug_id=l.bug_id and b.assigned_to=p.userid and b.bug_status in
1
2294
by: lukemack | last post by:
Hi, I have an array in the following format : Array ( =Array ( =Array (
11
7700
by: siva07 | last post by:
my $cStr="select distinct artist,company from albuminfo "; i am using this query to select unique artist and company. But the duplicates also get display. Is any idea. Thanks
2
3176
by: beargrease | last post by:
I'm kind of comfortable with basic joins, but a current project requires a complex query of many tables. The GROUP_CONCAT(DISTINCT ...) function has been very useful as returning my values as comma delimited values when joining multiple tables. I have one table called 'floorplans' which has two fields (floorplan_jpg & floorplan_pdf), I'd like each of these fields to return arrays of the same length (they have the same # of values in the data...
2
1811
rizwan6feb
by: rizwan6feb | last post by:
I have created a table (with only 2 fields) with the following query "CREATE TABLE `users` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , `name` VARCHAR( 20 ) NOT NULL ) ENGINE = MYISAM ;" There are 20,000 users in this table with ids from 1 to 20,000
0
9703
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10555
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10317
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10069
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7607
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6844
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5503
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4277
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3802
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.