Mysql将表分组为不同的值

时间:2015-07-30 15:06:04

标签: php mysql sql

我的数据库中有以下三个表:

书目:

+-----------+-----------------+
| filename  | books           |
+-----------+-----------------+
| fileone   | book1           |
| filetwo   | book1, book3    |
| filethree | book2, book4    |
| filefour  | book1           |
+-----------+-----------------+

产品:

+-----------+--------------------+
| filename  | products           |
+-----------+--------------------+
| fileone   | product3           |
| filetwo   | product1, product2 |
| filethree | product2, product3 |
| filefour  | product1           |
+-----------+--------------------+

compList:

+-----------+--------+-------+-------+-------+----------+----------+----------+
| filename  | title  | books1| books2| books3| products1| products2| products3|
+-----------+--------+-------+-------+-------+----------+----------+----------+
| fileone   | title1 | book1 |       |       | product3 |          |          |
| filetwo   | title2 | book3 | book1 |       | product1 | product2 |          |
| filethree | title3 | book4 | book2 |       | product2 |          | product3 |
| filefour  | title4 | book1 |       |       | product1 |          |          |
+-----------+--------+-------+-------+-------+----------+----------+----------+

我使用以下代码根据文件名连接前两个表:

$sql = "SELECT `books`,
    group_concat( DISTINCT `products` ) productList
    FROM bookList b
    JOIN productList p USING (`filename`)
    WHERE b.`books` <> ''
    AND p.`products` <> ''
GROUP BY `books`
"; 

所以我得到[{book:book1,product:product3},{book:book2,product:product2,product3} ...

我需要查询数据,以便获取文件名,标题以及相关产品和书籍。所以一个理想的输出将是

[{filname:fileone title:titl1 books:book1 products:product3},
{filename:filetwo title:title2 books:book1,book3 products:product1, product2}.....]

非常感谢有关如何执行此操作的一些提示。

1 个答案:

答案 0 :(得分:1)

所以这不是最有效的方法,但我必须创建另一个标题和文件名作为属性的视图。

我能够通过以下mySQL查询获得所需的结果:

//can't go any further
}