How to limit values when using distinct

前端 未结 4 1978
暗喜
暗喜 2021-01-22 10:30

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          


        
4条回答
  •  我在风中等你
    2021-01-22 10:49

    DISTINCT works on the entire row, not a single column. The only way to ensure not repeating rows is to exclude category column from the select.

    If your objective is to list all categories, you will have to either look up categories as you're looping over the query result set during output (not very efficient though) OR process your result set in the code before you output it by collapsing repeating rows and merging/concatenating category values into a string.

    You could try some fancy SQL with subqueries to convert categories into a single delimited string but that will sure make your code hard to read and query hard to debug.

提交回复
热议问题