mysql - SQL:如何获取表的列表对

标签 mysql sql select

需求:列出经常光顾同一酒吧的顾客对(即列出可能在咖啡吧相遇的所有顾客对)

酒吧 table :

-------------------------
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;

最佳答案

您可以将酒吧表与频繁表连接两次,然后继续连接以获取客户姓名。为了防止重复,您可以任意决定一个 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

<强> DBFiddle

关于mysql - SQL:如何获取表的列表对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53569127/

相关文章:

java - 在 jooq 中设置 NULL 值

php - 通过php从Mysql数据库中选择数据并随机显示其中的一些数据

mysql - MySql 中计算列的条件值

mysql - 选择相同条件存在 2 个不同值的 mysql 行

基于先前选择的 PHP 选择

mysql - 连接两个表并合并mysql中的公共(public)列

mysql - 为 mysql 查询指定两种不同的排序顺序

php - SQL table1 row_id 不显示 table2 row_id

php - 如果过期则从数据库中删除记录

javascript - 使用 php+mysql 和 jquery ajax post 填充三个后续选择列表