SQL:从两个与第三个相关的表中选择数据

时间:2018-04-17 22:59:27

标签: sql mariadb

我有三张桌子:

Table Relations(buyerID INTEGER, sellerID INTEGER)
buyerID and sellerID are foreign keys

+---------+---------+
| buyerID | sellerID|
+---------+---------+
|       1 |       3 |
|       2 |       3 |
|       3 |       2 |
|       4 |       1 |
|       5 |       2 |
+---------+---------+

Table Buyers(ID INTEGER, name VARCHAR(30), phone VARCHAR(10))
ID is a primary key
+----+-------+--------------+
| ID | name  | phone        |
+----+-------+--------------+
|  1 | Eric  | 9872554-1260 |
|  2 | Julia | 897-953-3210 |
|  3 | Josh  | 999-123-3250 |
|  4 | Martha| 098-213-8270 |
|  5 | Jill  | 909-457-3990 |
+----+-------+--------------+

Table Sellers (ID INTEGER, name VARCHAR(30), phone VARCHAR(10))


+---------+----------+--------------+
| ID      | name     | phone        |
+---------+----------+--------------+
|       1 | Nathan   | 321-45-6789  |
|       2 | Rob      | 112-22-3463  |
|       3 | Maria    | 404-040-0804 |
|       4 | Logan    | 305-954-7781 |
|       5 | Smith    | 810-123-5556 |
+---------+----------+--------------+

我需要使用Relations表打印SellerID,buyerID对,按代理名称排序。基本上,通过关系表,从第一个开始挑选每个卖家ID,并在进入下一个卖家之前将其与所有相关买家一起打印。 输出应如下所示:

+---------+------------+
|  Seller |    Buyer   |
+---------+------------+
|Maria    |   Eric     |
|Maria    |   Julia    |
|Nathan   |   Martha   |
|Rob      |   Josh     |
|Rob      |   Jill     |
+---------+------------+

我目前使用的声明如下:

SELECT s.name,b.name FROM Seller s, Buyers b
INNER JOIN Relations r ON (r.sellerID = s.ID )
ORDER BY s.name;

但是,这会在'on clause'中出现“未知列”r.sellerID“错误 我知道我在某种程度上滥用加入,但我现在确切地知道从哪里开始。任何帮助表示赞赏

2 个答案:

答案 0 :(得分:1)

我认为这会奏效:

SELECT
    b.name AS Seller,
    s.name AS Buyer
FROM
    Relations r
LEFT JOIN
    Buyers b
ON
    r.buyerID = b.ID
LEFT JOIN
    Sellers s
ON
    r.sellerID = s.ID
GROUP BY
    b.name,
    s.name
ORDER BY
    b.name,
    s.name

答案 1 :(得分:1)

要获得完全您输出的输出,您可以使用此查询(SQLFiddle)。请注意,它有一个奇怪的ORDER BY子句,因为按b.name排序会相对于您想要的更改最后两个条目(与Seller Rob匹配的条目)的顺序。您应该只使用b.name而不是b.id.

SELECT s.name AS Seller, b.name AS Buyer
FROM Relations r
JOIN Sellers s
ON r.sellerID = s.ID
JOIN Buyers b
ON r.buyerID = b.ID
ORDER BY s.name, b.id

输出:

Seller  Buyer
Maria   Eric
Maria   Julia
Nathan  Martha
Rob     Josh
Rob     Jill