-1

我有三个 A、B、C 表。

我怎样才能一次左加入A和B,同时右加入B和C?

例如,如果我有这些表:订单、产品、用户,我想要这样的查询:

SELECT Product.title, User.username, Order.id
FROM Order
/* relations: */
Order LEFT JOIN Product
Product RIGHT JOIN User
/* with this condition: */
ON Order.ProductID = Product.ID
ON Product.UserID = User.ID
4

1 回答 1

5

我不确定你在问什么,但是为了让你的上述语法正常工作,试试这个:

SELECT Product.title, User.username, Order.id
FROM Order
    LEFT JOIN Product
         ON Order.ProductID = Product.ID
    RIGHT JOIN User
         ON Product.UserID = User.ID

根据您想要的结果,我更喜欢使用LEFT JOINs可读性 - 所以如果您想要所有用户,无论他们是在产品表还是订单表中,那么这将起作用:

SELECT U.username, P.title, O.id
FROM User U
    LEFT JOIN Product P
         ON P.UserId = U.Id
    LEFT JOIN Order O
         ON O.ProductID = P.ID
于 2013-03-23T02:04:42.227 回答