如何在使用distinct时限制值

时间:2014-03-15 18:42:59

标签: mysql phpmyadmin

PHP

  SELECT DISTINCT bk.title AS Title, bk.year AS Year, aut.authorname AS Author, cat.category AS Category
         FROM book bk 

         JOIN book_category bk_cat 
         ON bk_cat.book_id = bk.bookid

         JOIN categories cat 
         ON cat.id = bk_cat.category_id

         JOIN books_authors bk_aut 
         ON bk_aut.book_id = bk.bookid

         JOIN authors aut
         ON aut.id = bk_aut.author_id

         ORDER BY bk.title ASC

enter image description here enter image description here

我的数据库正在回显以下数据,您可以看到如果它有多个类别,它会多次打印出来。从我的PHP代码可以任何人告诉我如何使它与类别列不同。感谢。

4 个答案:

答案 0 :(得分:1)

仅在所需列中实现不同数据的最简单方法是使用GROUP BY子句。默认情况下,它会根据列的值对行进行分组,仅显示不同的值,因此,如果要分组并仅显示不同的标题和类别,则应将查询编写为:

  SELECT bk.title AS Title, bk.year AS Year, aut.authorname AS Author, cat.category AS Category
  FROM book bk 

  JOIN book_category bk_cat 
  ON bk_cat.book_id = bk.bookid

  JOIN categories cat 
  ON cat.id = bk_cat.category_id

  JOIN books_authors bk_aut 
  ON bk_aut.book_id = bk.bookid

  JOIN authors aut
  ON aut.id = bk_aut.author_id

  GROUP BY  bk.title, cat.category
  ORDER BY bk.title ASC

正如您所看到的,没有使用DISTINCT,但您将获得所有具有区别标题和类别的书籍。您添加到GROUP BY子句中的字段越多,您获得的数据就越多。

同样,如果你只想按标题列出书籍,你应该只在GROUP BY条款中留下bk.title

答案 1 :(得分:0)

DISTINCT适用于整行,而不是单列。确保不重复行的唯一方法是从选择中排除类别列。

如果您的目标是列出所有类别,则必须在输出期间循环查询结果集时查找类别(尽管效率不高)或在输出结果集之前处理结果集通过折叠重复行并将类别值合并/连接成字符串。

您可以使用子查询尝试一些奇特的SQL,将类别转换为单个分隔的字符串,但这肯定会使您的代码难以阅读和查询难以调试。

答案 2 :(得分:0)

  SELECT DISTINCT bk.title AS Title, bk.year AS Year, aut.autName AS Author, cat.category AS Category
     FROM book bk 

     JOIN book_category bk_cat 
     ON bk_cat.book_id = bk.bookid

     JOIN categories cat 
     ON cat.id = bk_cat.category_id


     JOIN (SELECT GROUP_CONCAT(aut.authorname) as autName FROM authors JOIN books_authors ON books_authors.author_id=authors.author_id WHERE books_authors.book_id=bk.bookid) as aut


     ORDER BY bk.title ASC

答案 3 :(得分:0)

我想你可能想用group_concat()查看子查询,所以请试一试:

group_concat()将合并子查询的结果,并为您提供一个由逗号空格分隔的作者字符串,如author1, author2, author3

SELECT
    DISTINCT bk.title AS Title,
    bk.year AS 'Year',
    (
        SELECT
            group_concat(aut.authorname, ', ')
        FROM
            authors aut
            LEFT OUTER JOIN
                books_authors bk_aut
                ON
                    aut.id=bk_aut.author_id
        WHERE
            bk_aut.book_id = bk.book_id
    ) AS Author
FROM
    book bk
ORDER BY
    bk.title ASC