可以让MySQL在某些条件下忽略连接吗?

时间:2014-05-27 14:08:24

标签: php mysql join

以下代码成功地向我提供了登录人们所要求的书籍的详细信息,以及来自特定图书馆的书籍本身。

SELECT bookRequest.version, bookRequest.status, users.user_id, users.firstname, users.lastname, books.Author, books.Title
FROM users 
INNER JOIN bookRequest
ON users.user_id=bookRequest.user_id 
INNER JOIN books
ON bookRequest.bookID = books.ID
INNER JOIN libraryTokens
ON bookRequest.libraryID = libraryTokens.libraryID
WHERE libraryTokens.libraryID='". $libraryID ."'

bookRequest表还有一些列,用于直接存储不在系统中的书籍的手动添加请求,由未登录的人请求。在这种情况下,bookRequest.user_id始终为-1,额外列为bookRequest.firstname,bookRequest .lastname,bookRequest.Author和bookRequest.Title保留客人的姓名及其未列出的图书请求的详细信息。

我正在试图找出一种方法(我不知道它是否可能),当检索图书馆的书籍请求时,忽略

INNER JOIN bookRequest
ON users.user_id=bookRequest.user_id 
INNER JOIN books
ON bookRequest.bookID = books.ID

如果bookRequest.user_id为-1,则查询的一部分,而是检索bookRequest.firstname,bookRequest.lastname,bookRequest.Author和bookRequest.Title,但如果bookRequest.user_id> -1,则不会忽略连接。

是否可能,或者太乱了,而是我应该做两个单独的查询,并使用php组合生成的数组?

谢谢你看看。

1 个答案:

答案 0 :(得分:2)

您需要将JOIN更改为OUTER JOIN并在查询中添加CASE语句。像这样:

SELECT bookRequest.version, 
       bookRequest.status, 
       CASE WHEN bookRequest.user_id = -1 THEN bookRequest.user_id ELSE users.user_id END userid, 
       CASE WHEN bookRequest.user_id = -1 THEN bookRequest.firstname ELSE users.firstname END firstname, 
       ...
FROM bookRequest 
    JOIN libraryTokens
        ON bookRequest.libraryID = libraryTokens.libraryID
    LEFT JOIN books
        ON bookRequest.bookID = books.ID
    LEFT JOIN users 
        ON users.user_id=bookRequest.user_id 
WHERE libraryTokens.libraryID='". $libraryID ."'