0

我刚开始学习SQL。当我写这段代码时

create database tutorial_1;
use tutorial_1;
create table tutorial
(
id int primary key,
name varchar(40),
duration decimal(4,2),
date date
);
insert into tutorial(id, name, duration, date)
values(1, 'c', 23.12, '2014-02-10');
insert into tutorial
values(2, 'python', 12.45, '2014-02-11');
insert into tutorial
values(3, 'sql', 34.17, '2014-02-14');

create database tutorial_2;
use tutorial_2;
create table tutorial_info
(
tutorial_id int primary key,
views int(40),
likes int(40),
dislikes int(40),
shares int(40)
);
insert into tutorial_info(tutorial_id, views, likes, dislikes, shares)
values (1, 23411, 124, 12, 19);
insert into tutorial_info(tutorial_id, views, likes, dislikes, shares)
values (2, 29019, 920, 100, 234);
insert into tutorial_info
values (3, 9019, 129, 23, 8);
insert into tutorial_info

SELECT t.id, t.name,
ti.views, ti.likes, ti.dislikes, ti.shares
FROM tutorial AS t
JOIN tutorial_info AS ti
ON t.id=ti.tutorial_id;

在 SQL 文件上,操作输出显示:

错误代码:1146。表 'tutorial_2.tutorial' 不存在 0.000 秒

但是当我检查 SCHEMAS 上的表格时,我找到了那个表格。我该怎么做才能修复它?

4

2 回答 2

2

您正在创建两个单独的数据库:tutorial_1tutorial_2.

然后,您切换到tutorial_2数据库。之后,您将选择 和 之间的tutorial连接tutorial_infotutorialtutorial_1数据库中,而tutorial_infotutorial_2数据库中。由于您在tutorial_2数据库中,因此 MySQL 尝试从表中加载记录,该tutorial表中不存在tutorial_2数据库,因为它是在tutorial_1数据库中创建的。

编辑:我进行了一些实验,我相信您可以像这样进行跨数据库连接:

SELECT t.id, t.name,
ti.views, ti.likes, ti.dislikes, ti.shares
FROM tutorial_1.tutorial AS t
JOIN tutorial_info AS ti
ON t.id=ti.tutorial_id;
于 2015-07-25T17:23:09.027 回答
1

tutorial是一个数据库表tutorial_1,当您在数据库范围内工作时tutorial2(之后use tutorial_2)。所以你应该写:

SELECT t.id, t.name,
ti.views, ti.likes, ti.dislikes, ti.shares
FROM tutorial_1.tutorial AS t
JOIN tutorial_info AS ti
ON t.id=ti.tutorial_id;

一般来说,您应该只使用一个数据库。

于 2015-07-25T17:15:55.567 回答