从关联的 Toxi 表中检索数据
我正在使用典型的 MySQL 查询检索站点的部分数据,并从主表中回显各个字段等的结果,该主表的结构并不重要,但有一个唯一的 id,即“job_id
”与该“job_id”关联的多个类别我采用了一种 toxi 解决方案,该解决方案将类别与每个“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
)
我想要做的是,当我从主表中回显信息(使用“job_id”)时,我还想回显该 job_id 匹配的所有类别。
下面的查询仅返回 job_id 列出的第一个类别(tag_name),而它应该最多为六个(目前):
$query = "SELECT * FROM tags t
JOIN tag_relational r
ON t.tag_id=r.tag_id
WHERE r.job_id = $job_id";
$result=mysql_query($query) or die(mysql_error());
$cats=mysql_fetch_assoc($result);
在我的代码中,我使用它来回显匹配的类别:
<?php echo $cats['tag_name'];?>
有人可以解释一下如何我可以让所有类别名称都回显出来,而不仅仅是第一个? 谢谢 丹
顺便说一句,向 mu 太短道歉,当我上面有虚拟/不完整的信息时,他友好地回答了我的问题。
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=mysql_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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您只想列出类别名称,那么您可以使用
group_concat
有点像这样:当然,您需要一个适当的 WHERE 子句。这将为您提供
business
中的常用内容以及cats
中以逗号分隔的列表形式的类别名称。如果您还需要类别 ID,那么两个查询可能会更好:第一个查询获取
business
信息,第二个查询收集类别:其中
X
是逗号分隔的business
ID 值列表。然后你会在客户端修补问题。If you just want to list the category names, then you could use
group_concat
sort of like this: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 incats
.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:where
X
is a comma delimited list ofbusiness
ID values. Then you'd patch things up on the client side.