Jump to content

Is there a way to put a subquery into a single, comma seperated field?


Recommended Posts

I have two tables, users and phoneNumbers.

 

A user can have any amount of phone numbers.

 

I was to select all of a users phone numbers for a user, as a comma separate field. So, if Joe was my users name, and have 3 phone numbers, my recordset would look like:

 

id: 4

name: Joe

phoneNumbers: 555-5555, 567-7890, 754-9000

 

I was thinking something like:

 

select `id`, `name`, (select --- from phoneNumbers where phoneNumbers.owner=users.id) as `phoneNumbers`from users where `name`='Joe'

 

 

I am, I'm trying to combine them into one record when I do the select - Otherwise, I have to do a query, then do another query for each result, to get the phone numbers.

 

No you don't. Just do one query that gets all phone-numbers for a user.

Yeah, so if I have 100 users, I end up doing 101 queries.

 

$result = mysql_query("select `id`, `name` from users");

while($user = mysql_fetch_assoc($result)){
$sresult = mysql_query("select * from phoneNumbers where owner=".$user['id']); // gets called 100 times
// loop through phone numbers
}

 

Basically what I am trying to do is like a subquery, but where I turn several returned rows into one aggregate result.

I could use joins, but what I was looking for is a way to get a result set like:

 

id - name - phoneNumbers

1 - Dave - 555-555-5555, 555-555-5555

2 - Bob - 555-555-5555, 555-555-5555, 555-555-5555

 

So basically take and return multiple rows as a single value, almost like the count function.

i use someting similar for tags. and then i take the field and put them into an erray seperated by in my case  comma space

$tagsuh  = $row[tag];
$seperatetags = explode(", ", $tagsuh);
?>
<i><a href="search.php?tag=<?php echo $seperatetags[0]; ?>"><?php echo $seperatetags[0]; ?></a>,
<a href="search.php?tag=<?php echo $seperatetags[1]; ?>"><?php echo $seperatetags[1]; ?></a>,
<a href="search.php?tag=<?php echo $seperatetags[2]; ?>"><?php echo $seperatetags[2]; ?></a>,
<a href="search.php?tag=<?php echo $seperatetags[3]; ?>"><?php echo $seperatetags[3]; ?></a><?php } ?></i>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.