简体   繁体   English

PHP MySQL查询单个查询中的多个类别

[英]PHP MySQL Query Multiple Categories on a Single Query

I have an application that categorizes links for a tools page. 我有一个应用程序,可以对工具页面的链接进行分类。 On this page I want to have multiple categories and each tool under those categories. 在此页面上,我要具有多个类别,并且这些类别下的每个工具。 As I am going to have 13 categories (with more as the tool gets used) I don't want to run a query for each category. 由于我将要拥有13个类别(随着工具的使用,更多类别),我不想为每个类别运行查询。 I would prefer to run a single query to grab all the data. 我希望运行一个查询来获取所有数据。

Right now I have the page setup so that it displays each category with a drop down to view the tools. 现在,我有了页面设置,以便显示每个类别以及下拉菜单以查看工具。 What I need to do is have it so that only the tools for that category show up. 我要做的是拥有它,以便仅显示该类别的工具。 I'm having a problem working out how to go through all of that data from a single query. 我在解决如何从单个查询中遍历所有数据时遇到问题。

Currently I am using a while statement to run through the results as an array. 目前,我正在使用while语句将结果作为数组运行。

while($tools = $result->fetch_assoc()){
    if($tools['id'] = 1){
        echo $tools['name'];
    }
}

This is just a basic mockup of what I currently plan on doing. 这只是我目前计划做的一个基本模型。 I can't help thinking however there is a better way to go about this. 我不禁要思考,但是有更好的方法可以解决此问题。 What is the best way to grab a big chunk of data from MySQL and then break it out into categories with PHP? 从MySQL获取大量数据然后用PHP分解为几类的最佳方法是什么? If I need to run more than a single query that is fine, but I prefer not running a query for each category. 如果我需要运行多个查询就可以了,但是我不希望为每个类别运行一个查询。

If you don't have performance problems you can use GROUP_CONCAT function like this, 如果您没有性能问题,可以使用GROUP_CONCAT函数,

SELECT id,GROUP_CONCAT(name)
FROM tools
GROUP BY id

you may read more abut GROUP_CONCAT from mysql official web site here 你可以阅读更多紧靠GROUP_CONCAT从MySQL官方网站点击这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM