日期:2014-05-17  浏览次数:20317 次

求一简单SQL语句
user 表  
         
数据如下
u_id,u_name
 1    张三
 2    李四
 3    王五

product 表  
p_id,
p_userId,--管理员ID
p_consumerId--消费者ID
p_businesses--商家ID
p_count 数量

数据如下
p_id  p_userId  p_consumerId   p_businesses  p_count
1     1         2              3             100
2     1         3              2             200
 

其中 p_userId  p_consumerId   p_businesses  是外建,对应user表u_id


我想得到如下结果:
管理员   商家     消费用户    数量
张三     王五      李四       100
张三     李四      王五       200 



请教这个连接查询应该怎么写!谢谢!

------解决方案--------------------

select a.u_name 管理员,b.u_name 消费者,c.u_name 商家,p.p_count 数量
from product p,[user] a,[user] b,[user] c 
where p.p_userid=a.u_id and p.p_consumerId=b.u_id and p.p_businesses=c.u_id

------解决方案--------------------
--创建user表
CREATE  TABLE #USER(u_id INT,u_name NVARCHAR(10))
--插入user表数据
INSERT INTO #USER
SELECT 1,'张三'
UNION ALL
SELECT 2,'李四'
UNION ALL
SELECT 3,'王五'

--创建product表
CREATE TABLE #product(p_id INT,p_userid INT,p_consumerId INT,p_businesses INT,p_count INT)
--插入product表数据
insert into #product
SELECT 1,1,2,3,100
UNION ALL
SELECT 2,1,3,2,200


SELECT a1.u_name 管理员,a3.u_name 商家,a2.u_name 消费用户,p.p_count
  FROM #product p,#USER a1,#USER a2,#USER a3 WHERE 
p.p_userid = a1.u_id
AND p.p_consumerId = a2.u_id
AND p.p_businesses = a3.u_id

------解决方案--------------------
if object_id('userInfo','u') is not null
drop table userInfo
create table userInfo
(u_id int identity(1,1) primary key,u_name varchar(10))
insert into userInfo values('张三'),('李四'),('王五')

if object_id('product','u') is not null
drop table product
create table product
(
p_id int identity(1,1),
p_userId int references userInfo(u_id) ,
p_consumerId int references userInfo(u_id),
p_businesses int references userInfo(u_id),
p_count int
)
insert into product values(1,2,3,100),(1,3,2,200)

select * from userInfo
select * from product