现有
A表one two three三个字段
B表 id name 字段
A表的三个字段都是和B表的ID关联起来的。
问一下怎么样查询才能在查询的时候查出A表one two three 这三个值为id的对应name呢?
解决方案
10
SELECT B.name from B INNER JOIN A where A.one = B.id
UNION all
SELECT B.name from B INNER JOIN A where A.two = B.id
UNION all
SELECT B.name from B INNER JOIN A where A.three = B.id
SELECT B.name from B INNER JOIN A where A.one = B.id
UNION all
SELECT B.name from B INNER JOIN A where A.two = B.id
UNION all
SELECT B.name from B INNER JOIN A where A.three = B.id
SELECT DISTINCT * FROM (
SELECT B.name from B INNER JOIN A where A.one = B.id
UNION all
SELECT B.name from B INNER JOIN A where A.two = B.id
UNION all
SELECT B.name from B INNER JOIN A where A.three = B.id)t
60
和期望的结果有差距,无法进一步操作。
准确的说,想要的效果是查询结果是一条记录……能实现吗?
更正一下数据库结构:
A表:id、name、one、two、three
B表:id、name、parentid(B表自关联)
现在项目中的需求是,把全部的数据列表,每一条A记录占一行,A记录中one two three的位置显示为B表中对应的name。
请各位高手帮忙解答一下,谢谢!
语句:
--测试数据
;WITH A(id,name,one,two,three)AS(
select 1,"A",1,2,3 UNION ALL
select 2,"B",3,4,5
),B(id,name)AS
(
SELECT 1,"id1" UNION ALL
SELECT 2,"id2" UNION ALL
SELECT 2,"id2" UNION ALL
SELECT 3,"id3" UNION ALL
SELECT 4,"id4" UNION ALL
SELECT 5,"id5"
)
--测试数据结束
SELECT id ,
A.name ,
( SELECT TOP 1
name
FROM B
WHERE A.one = B.id
) AS one ,
( SELECT TOP 1
name
FROM B
WHERE A.two = B.id
) AS two ,
( SELECT TOP 1
name
FROM B
WHERE A.three = B.id
) AS three
FROM A;