如何在数据库中查询?

时间:2013-03-07 09:38:06

标签: sql

我有2张桌子

表1

Positon | Name | Nickname | Address
------------------------------------
   1    |   2  |    3     |    4
   5    |   6  |          |    7
   5    |   6  |          |    8

表2

Detail_seq | Details
--------------------
     1     |  manager
     2     |  Jimmy
     3     |  Jim
     4     |  Chicago
     5     |  Supervisor
     6     |  Mike
     7     |  Vancouver
     8     |  New York

,输出应该是这样或者什么

Position: Manager
Name: Jimmy
Nickname: Jim
Address: Chicago

Position: Supervisor
Name: Mike
Nickname:
Address: Vancouver and New York
如果不清楚,请随时提问。

提前致谢

4 个答案:

答案 0 :(得分:1)

以这种方式存储数据有点极端。我可以让您将数据类别存储在不同的表中。但如果你坚持,这应该有用

SELECT d1.details, d2.details, d3.details, d4.details
FROM main m, details d1, details d2, details d3, details d4
WHERE m.position = d1.detail_seq 
AND   m.name     = d2.detail_seq
AND   m.nickname = d3.detail_seq
AND   m.adress   = d4.detail_seq

答案 1 :(得分:1)

您需要为每个细节一次加入详细信息表:

  SELECT pos.Details, name.details, nick.details, adress.details
    FROM table1 t1
    LEFT JOIN table2 pos     ON pos.detail_seq = t1.position
    LEFT JOIN table2 name    ON name.detail_seq = t1.name
    LEFT JOIN table2 nick    ON nick.detail_seq = t1.nickname
    LEFT JOIN table2 address ON address.detail_seq = t1.address

答案 2 :(得分:1)

我认为这就是你想要的:

SELECT Position=manager.details, 
       Name=Name.details, 
       Nickname=Nickname.details, 
       Address=Address.details 
FROM   table1 t1 
       LEFT OUTER JOIN table2 manager 
                    ON t1.positon = manager.detail_seq 
       LEFT OUTER JOIN table2 name 
                    ON t1.name = name.detail_seq 
       LEFT OUTER JOIN table2 Nickname 
                    ON t1.nickname = Nickname.detail_seq 
       LEFT OUTER JOIN table2 Address 
                    ON t1.address = Address.detail_seq 

DEMO

答案 3 :(得分:0)

select (select details from t2 where t2.detail_seq=t1.position) position,
       (select details from t2 where t2.detail_seq=t1.name) Name,
       (select details from t2 where t2.det_seq=t1.nickname) nickname,
       (select details from t2 where t2.det_seq=t1.address) address
from t1 ;