无法正确实施加入

时间:2013-12-02 04:05:01

标签: php mysql

我想弄清楚

(book_id,branch_id,total_copies,number_available)

这是架构: enter image description here

到目前为止,我已经离开了:

SELECT
  TITLE,
  A.BOOK_ID,
  A.BRANCH_NAME,
  A.BRANCH_ID,
  NO_OF_COPIES,
  COUNT(BOOK_LOANS.BOOK_ID) AS NUM_OUT,
  NO_OF_COPIES - COUNT(BOOK_LOANS.BOOK_ID) AS NUM_AVAIL,
  AUTHOR_NAME                                      
FROM
  (SELECT
    TITLE,
    BOOK.BOOK_ID,
    BOOK_COPIES.BRANCH_ID,
    BRANCH_NAME,
    NO_OF_COPIES,
    BOOK_AUTHORS.AUTHOR_NAME                                          
  FROM
    BOOK,
    BOOK_COPIES,
    LIBRARY_BRANCH,
    BOOK_AUTHORS                                          
  WHERE
    BOOK_COPIES.BOOK_ID=BOOK.BOOK_ID 
    AND BOOK_AUTHORS.BOOK_ID = BOOK.BOOK_ID 
    AND (
      BOOK.TITLE LIKE :title 
      OR BOOK.BOOK_ID = :book_id 
      OR BOOK_AUTHORS.AUTHOR_NAME LIKE :author_name
    )                                          
    AND BOOK_COPIES.BRANCH_ID=LIBRARY_BRANCH.BRANCH_ID) AS A 
LEFT OUTER JOIN
  BOOK_LOANS 
    ON A.BOOK_ID=BOOK_LOANS.BOOK_ID 
    AND A.BRANCH_ID=BOOK_LOANS.BRANCH_ID 
GROUP BY
  A.BOOK_ID,
  A.BRANCH_ID

但我遇到的问题是,因为BOOK_AUTHORS表有一本书的多个作者。所以我能够理解只能加入BOOK和BOOK_AUTHORS的book_id,而我应该能够完全使用book_id和author_name。

因此,它为book_loans中的单个条目返回计数2次。

e.g。如果带有book_id的书可以说1234被签出一次,并且它的总副本为2,那么它应该将剩余的副本返回为1.但是它返回0。

请帮助我了解如何解决此问题。

注意:我正在使用php prepare语句。

1 个答案:

答案 0 :(得分:0)

我没注意你的查询(对我来说太复杂了),

  • COUNT(DISTINCT BOOK_LOANS.BOOK_ID)而不是COUNT(BOOK_LOANS.BOOK_ID)。如果你的查询工作得很好,除了它的计数,DISTINCT很有帮助。
  • 表现很重要。我猜内联视图太复杂了。我想知道是否改变了这个

    SELECT
        DISTINCT BOOK.BOOK_ID
    FROM
        BOOK INNER JOIN BOOK_AUTHORS USING(BOOK_ID)                                     
    WHERE
          BOOK.TITLE LIKE :title 
          OR BOOK.BOOK_ID = :book_id 
          OR BOOK_AUTHORS.AUTHOR_NAME LIKE :author_name
    
  • 然后最终查询看起来像这样

    SELECT
    TITLE,
    BOOK.BOOK_ID,
    LIBRARY_BRANCH.BRANCH_NAME,
    LIBRARY_BRANCH.BRANCH_ID,
    BOOK_COPIES.NO_OF_COPIES,
    COUNT(distinct BOOK_LOANS.BOOK_ID) AS NUM_OUT,
    BOOK_COPIES.NO_OF_COPIES - COUNT(distinct BOOK_LOANS.BOOK_ID) AS NUM_AVAIL,
    AUTHOR_NAME  
    
    FROM
      (
        SELECT
            DISTINCT BOOK.BOOK_ID
        FROM
            BOOK,
            BOOK_AUTHORS                                          
        WHERE
              BOOK.TITLE LIKE :title 
              OR BOOK.BOOK_ID = :book_id 
              OR BOOK_AUTHORS.AUTHOR_NAME LIKE :author_name
      ) AS A 
    INNER JOIN BOOK USING(BOOK_ID)
    INNER JOIN BOOK_AUTHORS USING (BOOK_ID)
    INNER JOIN BOOK_COPIES USING(BOOK_ID) 
    INNER JOIN LIBRARY_BRANCH USING(BRANCH_ID)
    LEFT OUTER JOIN
      BOOK_LOANS 
        ON BOOK.BOOK_ID=BOOK_LOANS.BOOK_ID 
        AND LIBRARY_BRANCH.BRANCH_ID=BOOK_LOANS.BRANCH_ID 
    GROUP BY
      BOOK.BOOK_ID,
      LIBRARY_BRANCH.BRANCH_ID,
      LIBRARY_BRANCH.BRANCH_NAME,
      BOOK_COPIES.NO_OF_COPIES,
      AUTHOR_NAME