create table area (
area_id int(11) not null auto_increment,
area_name varchar(60) not null,
primary key (area_id)
);
create table mainCategory(
mc_id int(11) not null auto_increment,
mc_name varchar(60) not null,
area_id int(11) not null,
primary key(mc_id),
foreign key(area_id) references area(area_id)
);
create table subCategory(
sc_id int(11) not null auto_increment,
sc_name varchar(60) not null,
mc_id int(11) not null,
area_id int(11) not null,
primary key(sc_id),
foreign key(mc_id) references mc(mc_id),
foreign key(area_id) references area(area_id)
);
create table shopes(
s_id int(11) not null auto_increment,
s_name varchar(60) not null,
s_address varchar(120) not null,
s_work varchar(255) not null,
s_imagepath varchar(255) not null,
s_image varchar(255) not null,
area_id int(11) not null,
mc_id int(11) not null,
sc_id int(11) not null,
primary key(s_id),
foreign key(area_id) references area(area_id),
foreign key(mc_id) references mc(mc_id),
foreign key(sc_id) references sc(sc_id)
);
我想用mysql join从四个表中选择数据。我正在使用
select s_name,s_address,s_work,s_image,area_name,mc_name from shopes inner join area on area.area_id=shopes.area_id inner join mainCategory on mc.area_id=area.area_id;
这是一个三表连接,它没有给出适当的结果。它给出了重复的结果。
答案 0 :(得分:1)
试试这个:
select s.s_name, s.s_address, s.s_work, s.s_image, a.area_name, mc.mc_name from shope as s LEFT JOIN area as a on a.area_id=s.area_id LEFT JOIN mainCategory as mc on mc.area_id=a.area_id LEFT JOIN subCategory as sc on sc.area_id=a.area_id
我使用了LEFT JOIN关键字而不是内连接,它返回左表(table1)中的所有行,右表(table2)中的匹配行。当没有匹配时,结果在右侧为NULL。
答案 1 :(得分:0)
使用此语法。
select a.coumn1,
a.coumn2,
b.coumn1,
c.coulumn1,
d.column1,
d.column2
from table1 a
left outer join table2 b
on a.id=b.id
left outer join table3 c
on b.id=c.id
left outer join table4 d
on a.id=d.id
where a.name = 'abc'
答案 2 :(得分:0)
select s_name, s_address, s_work, s_image, area_name, mc_name
from shopes, area, mainCategory
where shopes.area_id = area.area_id
and shopes.mc_id = mainCategory.mc_id;
如果仍有重复数据,请使用:
select distinct s_name, ...
答案 3 :(得分:0)
select s_name,s_address,s_work,s_image,area_name,mc_name
from area
inner join area
on area.area_id=shopes.area_id
inner join mainCategory
on mc.area_id=area.area_id;
答案 4 :(得分:0)
试试吧。 从shopes.area_id = area.area_id上的shopes join区域中选择shopes.s_name,s_address,s_work,s_image,area.area_name,maincategory.mc_name 在shopes.mc_id = maincategory.mc_id;
上加入maincategory