sql:如何获取表的列表对

3yhwsihp  于 2021-06-18  发布在  Mysql
关注(0)|答案(3)|浏览(328)

要求:列出经常光顾同一家酒吧的顾客对(即列出可能在咖啡馆遇到的所有顾客对)
吧台:

-------------------------
id| name                 
-------------------------
1 | Vivamus nibh         
2 | odio tristique       
3 | vulputate ullamcorper
4 | Cras lorem           
5 | libero est,

客户表:

-----------------------
id| name              
-----------------------
1 | Warren    
2 | Olympia            
3 | Logan
4 | Summer
5 | Kamal
6 | Fernandez

频率表:

-----------------
cust_id | bar_id
-----------------
1       | 1
2       | 1
3       | 2
4       | 2
5       | 3
6       | 4

预期输出:

---------------------------------------
customer1 | customer2 | barname
---------------------------------------
Warren    |  Olympia  | Vivamus nibh
Logan     |  Summer   | odio tristique

这是我的尝试,但没有成功:

select c1.name, c2.name, b1.name, b2.name
from frequents f1, frequents f2
join bar b1 on f1.bar_id = b1.id
join bar b2 on f2.bar_id = b2.id
join customer c1 on f1.cust_id = c1.id
join customer c2 on f2.cust_id = c2.id
where f1.bar_id = f2.bar_id;
iqjalb3h

iqjalb3h1#

您可以将bar表与frequent表联接两次,然后继续联接以获得客户名称。为了防止重复,您可以任意决定 cust_id 应小于另一个:

SELECT b.name, c1.name, c2.name
FROM   bar b
JOIN   frequents f1 ON f1.bar_id = b.id
JOIN   frequents f2 ON f2.bar_id = b.id AND f1.cust_id < f2.cust_id
JOIN   customer  c1 ON c1.id = f1.cust_id
JOIN   customer  c2 ON c2.id = f2.cust_id

D小提琴

m2xkgtsf

m2xkgtsf2#

为了得到每个酒吧的所有配对,自连接frequents表可以得到这个结果。
然后,您就可以在其他表的id上加入它们来获得名称。

SELECT 
cust1.name AS customer1, 
cust2.name AS customer2, 
bar.name AS barname
FROM frequents freq1
JOIN frequents freq2 ON (freq2.bar_id = freq1.bar_id AND freq2.cust_id > freq1.cust_id)
JOIN bar ON bar.id = freq1.bar_id
LEFT JOIN customer cust1 ON cust1.id = freq1.cust_id
LEFT JOIN customer cust2 ON cust2.id = freq2.cust_id
ORDER BY freq1.cust_id, freq2.cust_id, freq1.bar_id;

SQLFIDLE测试

ckocjqey

ckocjqey3#

我使用一个子查询来连接具有相同条但不同客户的频繁客户,还通过使用>来使用“排序”客户id以避免重复

SELECT c1.name customer1, f2.name customer2, b.name barname
FROM frequents f
JOIN customer c1 ON c1.id = f.cust_id
JOIN bar b ON f.bar_id = b.id
JOIN (SELECT cust_id, bar_id, name
      FROM frequents 
      JOIN customer ON id = cust_id) AS f2 ON f2.bar_id = f.bar_id AND f2.cust_id > f.cust_id

分贝小提琴:https://www.db-fiddle.com/f/npynegjadh4ypa6nqbiqot/1

相关问题