如何使用mysql join进行查询?

zpf6vheq  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(248)

嗨,我想在这个数据库上做一个左连接。
表格类别:

// `category` table has 3 columns 
id,business_id (FK from business),category.

餐桌业务:

// `business` table has 12 columns
id, name, etc (all info for that business)

我需要的是过滤所有的业务,是餐厅,并加入到各自的业务id。
问题是,每个业务都有多个类别,当我执行select/join时,结果不会返回不同的业务。
以下是我尝试的查询之一:

SELECT category.category,business.* 
FROM category 
INNER JOIN business 
ON category.business_id = business.id;

我也试过左,右连接。但我的电脑不是要花很长时间就是不能工作。p、 数据集是8.6g[数据库输出]:https://i.imgur.com/ef4zyor.png

fcg9iug3

fcg9iug31#

试试这个

SELECT *
FROM Business b
WHERE EXISTS (
    SELECT 1
    FROM Category
    WHERE category = 'Restaurants' AND business_id = b.id
)
wsxa1bj1

wsxa1bj12#

你的问题看起来没问题,但你只是在找餐馆。但是,首先,我要确保有一个基于category.id的索引

create index your_index_name on your_table_name(your_column_name);

然后可以通过以下方式简化查询:

select a.id, a.category, b.* from category a left join business b on a.business_id=b.id WHERE a.category='Restaurants';

即使这样,一张8.6克的table也需要时间。既然你说的是“pc”而不是“服务器”,那可能要花很长时间。

相关问题