开发者

Retrieving Data From Associated Toxi Table

开发者 https://www.devze.com 2023-03-25 13:48 出处:网络
I\'m retrieving my data for part of my site with a typical MySQL query and echoing out the results from various fields etc etc from my main table whose structure is not important but which has a uniqu

I'm retrieving my data for part of my site with a typical MySQL query and echoing out the results from various fields etc etc from my main table whose structure is not important but which has a unique id which is 'job_id'

In order to have multiple catagories associated with that 'job_id' i have employed a toxi solution which associates catgories to each 'job_id'.

TABLE `tags` (
`tag_id` INT NOT NULL AUTO_INCREMENT, 
`tag_name` VARCHAR(20) NOT NULL, 
PRIMARY KEY (`tag_id`)
)

CREATE TABLE `tag_relational` (
`job_id` INT NOT NULL, 
`tag_id` INT NOT NULL
)

What i want to do is, when i echo out the info from the main table (using 'job_id') i also want to echo all the catagories which that job_id is matched against.

The query below only returns the first catagory(tag_name) that the job_id is listed against, when it should be up to six (at the moment):

$query = "SELECT * FROM tags t
JOIN tag_relational r   
ON t.tag_id=r.tag_id
WHERE r.job_id = $job_id";

$result=mysq开发者_C百科l_query($query) or die(mysql_error());
$cats=mysql_fetch_assoc($result);

In my code i'm using this to echo out the matched catagories:

<?php echo $cats['tag_name'];?>

Can someone explain how i can get ALL the catagory names to echo out rather than just the first? Thanks Dan

BTW, apologies to mu is too short who kindly answered my question when i had dummy/less complete information above.


If you just want to list the category names, then you could use group_concat sort of like this:

select b.*,
       group_concat(c.category_name order by c.category_name separator ' ,') as cats
from business b
join tbl_works_categories w on b.id = w.bus_id
join categories c on w.category_id = c.category_name
where ...
group by b.id

You'd need a proper WHERE clause of course. That will give you the usual stuff from business and the category names as a comma delimited list in cats.

If you need the category IDs as well, then two queries might be better: one to get the business information and a second to collect the categories:

select w.bus_id, c.category_id, c.category_name
from tbl_works_categories w
join categories c
where w.bus_id IN (X)

where X is a comma delimited list of business ID values. Then you'd patch things up on the client side.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号