与源表不同的SQL连接

时间:2012-11-06 14:46:46

标签: sql

我有以下SQL语句:

select distinct
  u.id, 
  v1.code,
  v2.code,
  a1.phone,
  a1.phone1,
  SUM(o1.totalprice) as SALES
  SUM(ot4.numbers) as NUMBERS
from 
  users u,
  orders o2
 inner join values v1 on v1.pk = u.gender
 inner join values v2 on v2.pk = u.egistration
 inner join addresses a1 on a1.owner = u.pk 
 inner join orders o1 on o1.userpk = u.pk
 inner join orderthings ot4 on ot4.orderpk = o2.pk 
where 
  u.cccustomer = 1
and
  v2.code = 'REGISTERED'
group by
  u.id, 
  v1.code,
  v2.code,
  a1.phone,
  a1.phone1
order by 
  id;

基本上,订单上的连接不起作用,但我需要在与用户u无关的两个表上获得额外的关系。我怎么能做到这一点?

1 个答案:

答案 0 :(得分:1)

根据您的sample SQL Fiddle,如果您的表格彼此不相关,那么您可以使用CROSS JOIN加入它们,类似于:

select u.Email, 
  v1.String Gender, 
  v2.String Title, 
  o.a_string, 
  o.o_string
from users u
inner join value v1
   on u.Gender = v1.PK
inner join value v2
   on u.Title = v2.PK
cross join
(
  select a.PK, a.string a_string, o.string o_string
  from another a
  inner join other o
    on a.PK = o.PK
) o;

请参阅SQL Fiddle with demo