1

我有三个 mysql 表tblOnetblTwo并且tblThree

SELECT tblOne.bookID AS bookID,
  tblOne.title AS title,
  tblOne.author AS author,
  tblOne.blurb AS blurb,
  tblOne.isbn AS isbn,
  tblOne.coverImage As coverImage,
  CONCAT_WS(" ", tblThree.firstName, tblThree.lastName) AS fullName,
  tblTwo.rating,
  tblTwo.reviewText AS review,
  CONCAT_WS(" ", tblTwo.reviewDate, tblTwo.reviewTime) AS reviewDate
FROM tblTwo
INNER JOIN tblOne
  ON tblTwo.bookID = tblOne.bookID
INNER JOIN tblThree
  ON tblTwo.userID = tblThree.userID
WHERE tblTwo.bookID = 1000102;

输出填充了一个 XML 文件,对于这本书,有两个评论,因此,等的数据titleauthor提取了两次。我该如何克服这个问题,因为当我尝试从JavaScript查询中访问标签时,它会失败,因为它说它是未定义的。我认为这是由于有多个结果。

上面的 SQL 确实有效,我的 PHP 是错误的,但是......

即使没有,我该如何退回图书详细信息review?目前,只有经过审核的书籍才会返回其详细信息。

4

3 回答 3

1

您正在使用 INNER JOIN,它需要行存在于连接表中。改用 LEFT JOIN,即使左连接表中的行不存在,它也会返回第一个列出的表中的行:

SELECT tblBooks.bookID AS bookID,
    tblBooks.title AS title,
    tblBooks.author AS author,
    tblBooks.blurb AS blurb,
    tblBooks.isbn AS isbn,
    tblBooks.coverImage As coverImage,
    CONCAT_WS(' ', tblMembers.firstName, tblMembers.lastName) AS fullName,
    IFNULL(tblReviews.rating, '0'),
    tblReviews.reviewText AS review,
    CONCAT_WS(' ', tblReviews.reviewDate, tblReviews.reviewTime) AS reviewDate
FROM tblBooks 
LEFT JOIN tblReviews
    ON tblReviews.bookID = tblBooks.bookID
LEFT JOIN tblMembers
    ON tblReviews.userID = tblMembers.userID
GROUP BY 1, 2, 3, 4, 5, 7, 8;

请注意,我在 FROM 子句中列出了tblOne 第一个,即使有些书没有评论,这也是获取所有书籍所必需的。

null当没有评论时,您将不得不处理值。考虑使用IFNULL()生成空白或默认值,例如

IFNULL(tblTwo.rating, '') -- instead of just tblTwo.rating

或者

IFNULL(tblTwo.reviewText, 'None') -- instead of just tblTwo.reviewText

ETC

于 2013-04-30T22:01:02.580 回答
0

SQL 将始终在表之间形成笛卡尔积,这意味着如果您有一本书有 2 条评论并且每条评论有 3 个标签,那么您将返回 6 行以涵盖所有数据组合。

如果您要在每个连接的预期元素数大于 1 的表上连接,则每行不能有一本书。您将需要重组 XML 逻辑(不确定如何从 SQL -> XML 转换)以进行集群处理考虑到裁员。

于 2013-04-30T21:05:10.173 回答
0

使用 GROUP_CONCAT 并加入 table/table_three 结果。尝试类似:

SELECT tblOne.bookID AS bookID,
    tblOne.title AS title,
    tblOne.author AS author,
    tblOne.blurb AS blurb,
    tblOne.isbn AS isbn,
    tblOne.coverImage As coverImage,
    GROUP_CONCAT(
                (SELECT CONCAT_WS(" ", tblThree.firstName, tblThree.lastName) 
                           AS fullName,
                       tblTwo.rating,
                       tblTwo.reviewText AS review,
                       CONCAT_WS(" ", tblTwo.reviewDate, tblTwo.reviewTime) 
                           AS reviewDate
                FROM tblTwo     INNER JOIN 
                     tblOne ON tblTwo.bookID = tblOne.bookID
                                INNER JOIN 
                     tblThree ON tblTwo.userID = tblThree.userID
                     WHERE tblTwo.bookID = 1000102) 
                SEPARATOR ' '
                )
FROM tblTwo     INNER JOIN 
     tblOne ON tblTwo.bookID = tblOne.bookID
                INNER JOIN 
     tblThree ON tblTwo.userID = tblThree.userID
WHERE tblTwo.bookID = 1000102;
于 2013-04-30T21:10:10.477 回答