PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 29, 2022

[FIXED] How can I create a Group_Concat field per table using values from other records

 October 29, 2022     group-by, group-concat, left-join, mysql     No comments   

Issue

Suppose a table of First and Last Names and for each record I want to do comma-delimited list of relatives.

  • 1ST | LAST | RELATIVES
  • Bob | Smith | Alice,Andrew
  • Alice | Smith | Bob,Andrew
  • Andrew |Smith | Bob,Alice
  • Alex | Jones | Anny, Ricky
  • Anny | Jones | Alex, Ricky
  • Ricky | Jones | Alex, Anny

As per this sqlFiddle

http://sqlfiddle.com/#!9/25d80c/1

I know how to group_contact manually for any last name but am unclear how for each record I could have it go find the records with matching last name and run the same group_concat


Solution

You can do it with a self LEFT join and aggregation:

SELECT s1.First, s1.Last,
       GROUP_CONCAT(s2.First) Relatives
FROM Surnames s1 LEFT JOIN Surnames s2
ON s2.Last = s1.Last AND s2.First <> s1.First
GROUP BY s1.First, s1.Last;

See the demo.



Answered By - forpas
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing