具有连接条件的MySql查询

时间:2013-08-21 09:01:53

标签: mysql

我们假设我想要一份包含作者及其国家名称的所有书籍清单。 但我只想要着名作家,或者如果他们不出名,他们必须来自国家ID 123.

SELECT book.id, author.name, country.name
FROM book
LEFT JOIN author ON author.id = book.authorid
LEFT JOIN country ON country.id = author.countryid
WHERE author.famous = 1 OR (author.famous = 0 AND country.id = 123)

此查询为我提供了所有具有着名作者或国家123的书籍的列表。但我也想要没有作者的书籍,所以我添加“author.id is null or ...”

SELECT book.id, author.name, country.name
FROM book
LEFT JOIN author ON author.id = book.authorid
LEFT JOIN country ON country.id = author.countryid
WHERE (author.id is null or (author.famous = 1 OR (author.famous = 0 AND country.id = 123)))

但在这里我们遇到了一个问题,现在我们所有的书籍都有着名作家或国家123的作者以及没有作者的书籍。

但是那些有着名作者并且不是来自国家123的作者的书籍不在列表中。如何在1个查询中管理这个?或者这是不可能的,我需要一个子查询吗?

我应该在多个表上加入条件,但这是不可能的。

谢谢!

修改 只是为了确保每个人都能理解这个问题。最后,我想要一份所有我的书籍清单,在书籍旁边我想要作者的信息,但前提是作者很有名,或者他是来自countryid 123.

我的查询有错,所以这里是一个更好的查询

SELECT book.id, author.name, country.name
FROM book
LEFT JOIN author ON author.id = book.authorid
LEFT JOIN country ON country.id = author.countryid
WHERE author.id is null OR author.famous = 1 OR country.id = 123

但是有了这个问题,我仍然没有从乡下人国外123那里得到一本非着名作家的书。我希望这些书在列表中没有作者信息。

所以当作者不出名而不是来自countryid 123时,我不想和作者一起加入这本书!

4 个答案:

答案 0 :(得分:1)

首先,您的第一个查询有误。在这里author.famous = 1 OR (author.famous = 1 AND country.id = 123)你只能获得作者所着名的书籍 AND 来自123.也许你的意思是author.famous = 1 OR (author.famous = 0 AND country.id = 123),但这也没有用。两个条件就足够了。

你可以写:

SELECT book.id, author.name, country.name
FROM book
LEFT JOIN author ON author.id = book.authorid
LEFT JOIN country ON country.id = author.countryid
WHERE (author.famous = 1 OR country.id = 123)

对于第二个查询,请尝试以下操作:

SELECT book.id, author.name, country.name
FROM book
LEFT JOIN author ON author.id = book.authorid
LEFT JOIN country ON country.id = author.countryid
WHERE (author.id is null OR author.famous = 1 OR country.id = 123)

答案 1 :(得分:1)

请尝试使用此查询:

SELECT book.id, author.name, country.name
FROM book
LEFT JOIN author ON author.id = book.authorid
LEFT JOIN country ON country.id = author.countryid
WHERE author.id is null or author.famous = 1 or (author.famous = 0 AND country.id = 123)

我也改变了

or (author.famous = 1 AND country.id = 123)

or (author.famous = 0 AND country.id = 123)

因为

  

或者如果他们出名,他们必须来自国家/地区ID 123

实际上它与你的查询没什么不同,我只是省略了过时的parantheses,但我不明白,为什么它不应该工作。您确定,您的数据库中确实存在没有作者的书籍吗?

答案 2 :(得分:0)

尝试此查询,您可以获得任何书籍:

SELECT book.id, if(author.famous <> 0 or country.id = 123,GROUP_CONCAT(author.*),null), country.name
FROM book
LEFT JOIN author ON author.id = book.authorid
LEFT JOIN country ON country.id = author.countryid

由于

答案 3 :(得分:0)

假设作者在author.famous = 1时出名并且在0为0时不出名,那么你的第一组条件看起来不对,它看起来目前仅过滤给着名作者而不管国家,它应该是:

WHERE author.famous = 1 OR country.id = 123

如果你要找的最终数据是合并的:

  • 所有着名作家的书籍(不论国家)
  • 来自国家ID的所有书籍均为123(无论名气如何)
  • 所有没有作者的书籍(不论国家)

你的条件是:

WHERE author.famous = 1 OR country.id = 123 OR author.id is null