如何获取X及其推荐人的记录?

问题描述 投票:0回答:1

我有3张桌子。

Orders (id, total_price, receiver_cient_id)
Clients (id, name, status)
Referals (id, name, client_id)

添加订单时,有时接收者是CLIENT,有时是REFERRAL,所以receiver_client_id可以同时具有client_idreferral_idReferralsClients 添加,这就是我将 client_id 存储在 referrals 表中的原因。

样本数据:

Orders                 Clients                  Referals
----                   ----                     ----
1, 350, 15032          15010, "Alex", 1         7809100, "Jay", 15010
2, 440, 16500          15011, "Jacob", 1        7809101, "Jean",15010
3, 210, 18023          15012, "Sam", 0          7809102, "Hew", 15011
4, 900, 15032          15032, "John", 1         7809123, "Aldo",15032
5, 330, 7809123        15040, "Sandy", 0        7809124, "Sew", 15032

我想在一次查询中获取 id 为 15032 的客户的所有订单及其推荐人的订单。是否可以? 预期结果:

1, 350, 15032
4, 900, 15032
5, 330, 7809123

我做了什么:

select * from orders AS o JOIN
  (SELECT id FROM clients where id = 15032
   UNION
  SELECT id FROM referals where referals.client_id = 15032) AS c
on o.receiver_client_id = c.id

但这并不正确。我怎么知道 referal_id 不是 别人的 client_id? 1 年后,client_ids 将增加到 7809100(与 referal_id 相同)。他们不会混在一起吧?结果也会带来错误的客户订单。

sql mysql join union
1个回答
0
投票

添加订单时,有时接收者是CLIENT,有时是CLIENT 推荐...

这是否意味着推荐人也是客户?
为什么要把它们放在单独的表中?

将您的设计更改为类似这样的内容(带有示例数据):

CREATE TABLE Clients (
  id INT PRIMARY KEY, 
  name VARCHAR(255), 
  status INT, 
  referred_by INT REFERENCES Clients(id)
);

INSERT INTO Clients VALUES
  (15010, 'Alex', 1, null), (15011, 'Jacob', 1, null), (15012, 'Sam', 0, null), (15032, 'John', 1, null), (15040, 'Sandy', 1, null),
  (15100, 'Jay', null, 15010), (15101, 'Jean', null, 15010), (15102, 'Hew', null, 15011), (15103, 'Aldo', null, 15032), (15104, 'Sew', null, 15032);

CREATE TABLE Orders (
  id INT PRIMARY KEY, 
  total_price DECIMAL(10,2), 
  cient_id INT REFERENCES Clients(id)
);
INSERT INTO Orders VALUES
  (1, 350, 15032), (2, 440, 15102), (3, 210, 15040), (4, 900, 15032 ), (5, 330, 15103);

那么你只需要一个简单的连接:

SELECT *
FROM Clients c INNER JOIN Orders o
ON o.cient_id = c.id
WHERE 15032 IN (c.id, c.referred_by);

查看演示

© www.soinside.com 2019 - 2024. All rights reserved.