从2个表中重新搜索数据

时间:2017-03-25 05:57:06

标签: mysql sql sql-server oracle greatest-n-per-group

我有两张表格如下。

  • 表1:customer,columns:customer_id,source
  • 表2:来源,列:来源,等级

一个客户会有很多来源,每个来源在排名表中都有一个特定的排名,我需要以这样的方式获取数据:对于每个拥有最低排名来源的个人客户,我需要获取这些记录。

以下是一个例子:

客户表数据

1 abc
2 efg
3 abc
1 efg
1 hij
2 hij

源表数据是

abc 2
hij 1
efg 3

结果集应为:

1 hij
2 hij
3 abc

4 个答案:

答案 0 :(得分:1)

您可以使用以下两个查询之一来满足您的要求。

QUERY 1

   [SyncVar]//server to client. sync this variable name across all clients

   public string localPlayerName = "Player";

   void OnGUI()
    {
        if (isLocalPlayer)
        {
            localPlayerName = GUI.TextField(new Rect(0, 0, 100, 20), localPlayerName);

            if (GUI.Button(new Rect(110, 0, 100, 20), "Name"))
            {
                CmdUpdateLocalPlayerName(localPlayerName);

            }
        }
    }

    [Command]//client to server
    void CmdUpdateLocalPlayerName(string userName)
    {
        localPlayerName = userName;
    }

QUERY 2

SELECT c.customer_id, 
       c.source 
FROM   customer c 
       INNER JOIN source s 
               ON c.source = s.source 
WHERE  s.rank = (SELECT Min(s1.rank) 
                 FROM   source s1 inner join customer c1 on s1.source = c1.source
                 WHERE  c1.customer_id = c.customer_id)

更新1

此更新是对3个表而不是2个表的评论的回应。当您的架构分布在3个表中时,下面的查询会扩展查询1

SELECT x.customer_id ,
       c1.source
FROM
  (SELECT c.customer_id ,
          MIN(s.rank) AS MinRank
   FROM customer c
   INNER JOIN SOURCE s ON c.source = s.source
   GROUP BY c.customer_id) x
INNER JOIN customer c1 ON x.customer_id = c1.customer_id
INNER JOIN SOURCE s1 ON s1.source = c1.source
AND s1.rank = x.MinRank;

答案 1 :(得分:0)

对于Oracle:

select d.customer_id, d.source
from (
    select
        c.customer_id,
        s.source,
        row_number() over (partition by c.customer_id order by s.rank asc) as rn
    from customer c
        join source s
            on c.source = s.source
) d
where d.rn = 1
;

答案 2 :(得分:0)

一种更简单的方法。试试这个 -

select c.cid,c.sourceid,min(s.rankid)
from customer c inner join sourc s 
on (c.sourceid=s.sourceid) 
group by c.cid order by c.cid asc 

这是SQLFiddle

答案 3 :(得分:0)

Select a.customer_id,b.source
from
(select c.customer_id,min(s.rank) as rank
from customer c 
inner join source s 
on c.source=s.source 
group by c.customer_id) as a
inner join source b
on a.rank = b.rank