MySQL:如何从2个表中获得结果而不重复结果?

时间:2013-12-06 18:17:18

标签: mysql

我有3张桌子:book,publisher,book_category

对于特定的图书类别(幻想),我必须显示提供该类型的出版商名称列表。

publisher_name和category_name通过book table链接,因此我的查询是:

SELECT publisher.publisher_name
FROM publisher, book, book_category
WHERE publisher.publisher_id = book.publisher_id
AND book.category_id = book_category.category_id
AND category_name =  'fantasy';

但如果该出版商提供了多本幻想书,那么我得到的结果就是重复出版商的名字。

假设我有“霍比特人”和“指环王”,两者都是幻想,由同一个出版商A提供。 在这种情况下,我的查询结果是:

PublisherA

PublisherA

是否可以只获得一次结果?即使有超过2本幻想书 由同一出版商出版?

4 个答案:

答案 0 :(得分:4)

如果您只需要publisher_name

,请使用distinct
SELECT distinct publisher.publisher_name

顺便说一句,尝试使用JOIN语法...来连接表

SELECT distinct p.publisher_name
FROM publisher p
join book b on b.publisher_id = p.publisher_id
join book_Category bc on bc.category_id = b.category_id
where bc.category_name = 'fantasy'

答案 1 :(得分:3)

使用DISTINCT

SELECT DISTINCT publisher.publisher_name
FROM publisher, book, book_category
WHERE publisher.publisher_id = book.publisher_id
AND book.category_id = book_category.category_id
AND category_name = 'fantasy';

答案 2 :(得分:0)

尝试将此添加到查询的末尾:GROUP BY publisher.publisher_name

答案 3 :(得分:0)

每个人都提到DISTINCT,这是正确的(better than GROUP BY in MySQL, because of the way the optimizer is set up),但我想我还会为性能增强添加修改。

目前,您有隐式交叉连接来访问其他表,并且由于过滤顺序,使这些显式INNER JOIN s会提高效率。例如:

SELECT DISTINCT Publisher.publisher_name
FROM publisher Publisher
INNER JOIN book Book ON Publisher.publisher_id = Book.publisher_id
INNER JOIN book_category Book_Category ON Book.category_id = Book_Category.category_id
WHERE Book_Category.category_name = 'fantasy';

在原始查询中,您引入了所有三个表(publisherbookbook_category)的完整记录集,然后从该集合中加入相应的键,然后返回结果集。在此新查询中,您对Book_Category的连接仅基于Publisher和Book之间的连接返回的记录集。如果基于此联接发生过滤,您将看到性能提升。

您还可以获得符合ANSI标准的附加好处,以及显式编码,以提高维护的便利性。