EllisLab text mark
Advanced Search
     
SQL Joining two tables to show one row
Posted: 05 October 2010 02:11 AM   [ Ignore ]
Joined: 2010-09-22
52 posts

OK Here is my case if this is not possible, please help me out with the next one:
  I have three tables, one is accounts, the other two tables can have more than one row for each user account, but when I run the query using only codeigniter’s syntaxes, I get multiple rows, is it possible, for example, if there is user Jon and multiple rows in table subjects that match with jon’s id to show in one line (Ex: Jon/subject1/subject 2 not Jon/subject1 Jon/subject2) do this for all three tables, I got the joining part but I can’t figure out how to make it show in one line.

If the above is not possible, is it possible to do the same with two tables, for example second table has multiple rows matching with user id, to show all $row->subject; in one row like Jon/subject1/subject2/subject3 those subjects are different rows with unique id’s but same user ids, currently for me it shows this

jon/subject1
Jon/subject2

Thanks in advance.

 
Posted: 05 October 2010 02:48 AM   [ Ignore ]   [ # 1 ]   [ Rating: 0 ]
Avatar
Joined: 2008-11-18
678 posts

if you are using mysql, take a look at Group_Concat.
I think that may be what you are looking for.
Using your example, you would use it like:

select accounts.username as usergroup_concat(subjects.name) as subjects from accounts join subjects on subjects.account_id accounts.id 

and it would return one row like

user Jon
subjects 
subject2,subject3 

You can change the separator to the forward slash (as you have it in your example), but doing something like:

select accounts.username as usergroup_concat(subjects.name SEPARATOR '/') as subjects from accounts join subjects on subjects.account_id accounts.id 

and that would return

user Jon
subjects 
subject2/subject3 
 Signature 

Quality Coder | Looking for work? | Logo by InsiteFX

 
Posted: 05 October 2010 02:58 AM   [ Ignore ]   [ # 2 ]   [ Rating: 0 ]
Joined: 2010-09-22
52 posts

thanks for the reply! I will do this and let you know if it worked

 
Posted: 05 October 2010 10:12 AM   [ Ignore ]   [ # 3 ]   [ Rating: 0 ]
Avatar
Joined: 2009-12-08
1804 posts

if you use group_concat, you must include a group_by.

SELECT accounts.username AS userGRUOP_CONCAT(subjects.name SEPARATOR '/') AS subjects FROM accounts JOIN subjects ON subjects.account_id accounts.id GROUP BY accounts.id 
 Signature 

@basdflasjk | BitAuth: Authentication and Role-based Permissions | Session Library Replacement


Please read the User Guide! (Upgrading from a previous version?)