php - 查询从多个表中选择

标签 php mysql

我知道有几篇关于此的帖子,但我无法让它发挥作用。我没有任何MySQL“join”或“left”的经验,只有简单的查询。

我有 3 个表:类别、公司和 catcomp

类别

id | name | ... | ... |

1 | Foo

2 | Bar

公司

id | name | ... | ...

1 | Company1

2 | Company2

Catcomp(为一家公司存储多个类别)

company_id | category_id

1 | 1

1 | 2

2 | 2

我只有这个:

$result = mysql_query("SELECT * FROM categories");
while($row = mysql_fetch_array($result))
{
    echo '<input type="checkbox" id="'.$row['id'].'" name="cat[]" value="'.$row['id'].'">'.$row['name'].'<br>
}

这会打印出带有复选框的所有类别。我希望为当前公司选中这些框。

有什么想法吗?

最佳答案

可能有更优雅的解决方案,但无论如何......

DROP TABLE IF EXISTS categories;
CREATE TABLE categories 
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,name VARCHAR(12) NOT NULL UNIQUE
);

INSERT INTO categories VALUES
(1 ,'Foo'),(2,'Bar'),(3,'Boo');

DROP TABLE IF EXISTS companies;
CREATE TABLE companies 
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,name VARCHAR(12) NOT NULL UNIQUE
);

INSERT INTO companies VALUES
(1,'Company1'),(2,'Company2'),(3,'Company3');;


DROP TABLE IF EXISTS company_category;
CREATE TABLE company_category
(company_id INT NOT NULL,category_id INT NOT NULL,PRIMARY KEY(company_id,category_id));

INSERT INTO company_category VALUES (1 ,1),(1 ,2),(2 ,2);

SELECT o.id company_id
     , o.name company_name
     , a.id category_id
     , a.name cateory_name
     , CASE WHEN oa.company_id IS NOT NULL THEN ' checked' ELSE '' END checked
  FROM companies o
  JOIN categories a
  LEFT 
  JOIN company_category oa
    ON oa.company_id = o.id
   AND oa.category_id = a.id;

 +------------+--------------+-------------+--------------+----------+
 | company_id | company_name | category_id | cateory_name | checked  |
 +------------+--------------+-------------+--------------+----------+
 |          1 | Company1     |           1 | Foo          |  checked |
 |          2 | Company2     |           1 | Foo          |          |
 |          3 | Company3     |           1 | Foo          |          |
 |          1 | Company1     |           2 | Bar          |  checked |
 |          2 | Company2     |           2 | Bar          |  checked |
 |          3 | Company3     |           2 | Bar          |          |
 |          1 | Company1     |           3 | Boo          |          |
 |          2 | Company2     |           3 | Boo          |          |
 |          3 | Company3     |           3 | Boo          |          |
 +------------+--------------+-------------+--------------+----------+

http://www.sqlfiddle.com/#!2/11e6e/1

关于php - 查询从多个表中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18147175/

相关文章:

php - 具有多个参数的一种方法还是具有一个参数的多种方法?

php - 如何在 opencart 主题中更改 .twig 中的代码

mysql - 查询以合并 mysql 上的 2 个表

php - mySQL结合表查询中的数据

mysql - 如何将变量传递给 IN 子句?

php - 如何从单个字段中查找超时和超时并将其值提取到 SQL 中的另一个表

php - phpunit/phpunit ^6.2 安装失败

PHP 安全地登录到 mysql 但如果失败则继续脚本

php - 创建菜单时将 url 包含在 mysql 字段中

php - mysqli_insert_id 是否有可能在高流量应用程序中返回错误的 id?