My tables are:
Parent_Child (Parent_SSN, Child_SSN)
Person (SSN, Name, age, sex)
School (Child_SSN, School_Name)
I want to select the parents(female,male) who have atleast one of their children in a particular school 'X'
.I have a working query and my mysql query is:
select group_concat(p.name) from person p,parentchild pc,school s
where s.schoolname='X' and s.childssn=pc.childssn and p.ssn=pc.parentssn
group by pc.childssn
This displays the result as parent(male,female)
but I want the result in (female,male) form
and if I group it by parent.sex it displays results in individual rows and not in a single row.I am out of ideas.
Sample desired output:
name
Angela,Jim
Output of my above existing query:
name
Jim,Angela
Here's a Sql Fiddle for you.
SELECT DISTINCT group_concat(p.name ORDER BY p.sex Asc)
FROM Person p JOIN Parent_Child pc ON p.ssn=pc.Parent_SSN
JOIN School s ON s.Child_SSN = pc.Child_SSN
WHERE s.School_Name='X'
GROUP By pc.Child_SSN;
Try this, might possible using sort
SELECT GROUP_CONCAT( p.name ORDER BY p.name DESC ) from person p,parentchild pc,school s
where s.schoolname='X' and s.childssn=pc.childssn and p.ssn=pc.parentssn
group by pc.childssn
You can use ORDER BY inside the GROUP_CONCAT function in this way :
Try this
SELECT group_concat(DISTINCT p.name ORDER BY p.name Asc)
FROM person p JOIN parentchild pc ON p.ssn=pc.parentssn
JOIN school s ON s.childssn = pc.childssn
WHERE s.schoolname='X'
GROUP By pc.childssn
See http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function%5Fgroup-concat
I somehow managed to get the results using join here is my working query.
select * from (select distinct p.name from person p,parentchild pc,school s where s.schoolname='X' and s.childssn=pc.childssn and p.ssn=pc.parentssn and p.sex='F')q1 join (select distinct p.name from person p,parentchild pc,school s where s.schoolname='X' and s.childssn=pc.childssn and p.ssn=pc.parentssn and p.sex='M')q
I want to still know whether it is possible to sort items by a particular condition in group_concat result set which will affect it's postion in the group_concat result set.
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.