SQL查询2行,只显示一次具有相同值的行

时间:2013-10-04 16:03:13

标签: php html mysql sql rows

我有这两个表,BOOK和REVISION,有点像这样:

Book
Book_ID  |  Book_Name |
======================
1        |      Book 1|
2        |      Book 2|
3        |      Book 3|
4        |      Book 4|
Revision
Rev_Book_ID  |  Date_Modified |
===========================
1            |      10/1/2012   |
2            |      10/3/2012   |
2            |      10/5/2012   |
4            |      10/6/2012   |

当书籍被修改时,书籍的book_id将保存在修订表中。如果该书再次被修改,它将添加该书的另一行。在我的SQL查询中,结果是它显示了本书的2个修订版。

这是我的疑问:

SELECT book.Book_ID, book.Book_Name, Revision.Rev_Book_ID  from Book INNER JOIN Revision ON book.Book_ID=Revision.Rev_Book_ID

还有修订结果(PHP问题)我怎么能实现这个,如果书被修改两次它将显示2个修订或3如果3修订,我知道这是一个if和else但没有想法如何做到这一点。

My Result:

Book ID   |  Book Name     | Revisions        |
==============================================
1         |     Book 1     | 1 Revision       | 
2         |     Book 2     | 2 Revision       | 
2         |     Book 2     | 2 Revision       | 
3         |     Book 3     | No Revision      | 
4         |     Book 4     | 1 Revision       | 
Want Result
Book ID   |  Book Name     | Revisions        |
==============================================
1         |     Book 1     | 1 Revision       | 
2         |     Book 2     | 2 Revision       | 
3         |     Book 3     | No Revision      | 
4         |     Book 4     | 1 Revision       | 

3 个答案:

答案 0 :(得分:0)

您可以按book_id进行分组,只选择这些==到MAX(Rev_Book_ID)的rev_book_ids 通常,您希望每本书对数据进行同步。 这是mysql规范:http://dev.mysql.com/doc/refman/5.5/en/group-by-functions.html 它应该给你很多想法

答案 1 :(得分:0)

对于每本书,您需要修改的数量(COUNT(Date_Modified)):

   SELECT Book_ID, Book_Name, COUNT(Date_Modified) AS "Revisions"
     FROM Book
LEFT JOIN Revison
       ON Book_ID = Revision_Book_ID
 GROUP BY 1, 2

答案 2 :(得分:0)

假设你只是想摆脱重复:

SELECT book.Book_ID, book.Book_Name, Revision.Rev_Book_ID from Book 
INNER JOIN Revision ON book.Book_ID=Revision.Rev_Book_ID GROUP BY book.Book_ID