如何从多个表中有效地获取数据?

时间:2014-08-28 11:34:45

标签: mysql sql database

我希望使用单个查询来显示所有表中的数据。我如何有效地从这个表中获取数据

this is my database tables

以下是我的预期输出: enter image description here

我试过像这样给出了错误。

select b_id,
b_datetime,
invoice_id,
plan_id,
exp_datetime,
plan_name,
plan_amount,
months,
s_name,
s_url,
name
amount 
from tblplanboughts pb,tblplans p , tblshops s , tblusers u 
where pb.uid=u.uid && 
pb.plan_id=p.plan_id && u.uid=s.uid;

2 个答案:

答案 0 :(得分:1)

简单Inner join将解决您的问题:

select pb.b_datetime, pb.invoice_id, p.plan_name, p.months, pb.amount, s.s_name, s.s_url, u.name, pb.exp_datetime
from tblplanboughts pb, tblpricingplans p, tblshops s, tblusers u
where pn.b_id=s.b_id and pb.plan_id=p.plan_id and pb.uid=u.uid

使用带有Join关键字的内部联接

select pb.b_datetime, pb.invoice_id, p.plan_name, p.months, pb.amount, s.s_name, s.s_url, u.name, pb.exp_datetime
from tblplanboughts pb inner join tblpricingplans p on pb.plan_id=p.plan_id
                       inner join tblshops s on pb.b_id=s.b_id
                       inner join tblusers u on pb.uid=u.uid

答案 1 :(得分:0)

只需在From子句中使用别名,然后在表之间的关系字段上应用连接:

select pb.*, p.* , s.* , u.*

from tblplanboughts pb, tblpricingplans p, tblshops s, tblusers u

where pn.b_id=s.b_id and pb.plan_id=p.plan_id and pb.uid=u.uid

你也可以在where子句

中使用inner join...on语句而不是use(=)