用于匹配卖家和买家的SQL查询

时间:2012-01-31 14:37:35

标签: mysql sql

好的,我有一张桌子上有人。一张桌子上有赠送的物品,一张放有人们想要的物品。

People:
Person_ID, Name

Giveaways:
Person_ID, Item_ID

Wishlist:
Person_ID, Item_ID

所以我想要一个返回特定用户的交换建议的查询。

因此,如果我想要人A的交换建议,它应该返回一个人的列表,这些人放弃了人A想要的项目,并且想要一个人A给予的项目。 结果应该包括:人员A的项目,人名也与id和item_ID交换。

3 个答案:

答案 0 :(得分:1)

@SérgioMichels的回答应该是正确的。但它没有得到卖方的名字,它使用的语法应该(在我看来)应该避免。

所以,这是另一种选择......

SELECT
  buyer.name          AS buyer,
  buyerWants.name     AS buyer_wants,      (assuming the items have names),
  buyerHas.name       AS buyer_has,
  seller.name         AS seller,
  sellerWants.name    AS seller_wants,
  sellerHas.name      AS seller_has
FROM
  People              AS buyer
INNER JOIN
  Wishlist            AS buyerWants
    ON buyerWants.person_id = buyer.person_id
INNER JOIN
  Giveaways           AS sellerHas
    ON sellerHas.item_id = buyerwish.item_id
INNER JOIN
  People              AS seller
    ON seller.person_id = sellerHas.seller_id
INNER JOIN
  WishList            AS sellerWants
    ON sellerWants.person_id = seller.person_id
INNER JOIN
  GiveAways           AS buyerHas
    ON  buyerHas.item_id = sellerWants.item_id
    AND buyerHas.person_id = buyer.person_id
WHERE
  buyer.person_id = ?

答案 1 :(得分:0)

我认为你需要的是这样的:

select p.*
     , w.item_id  item_wanted
     , g.person_id  person_giveaway
  from People p
     , Wishlist w
     , Giveaways g
 where p.person_id = ?
   and p.person_id = w.person_id
   and g.person_id != p.person_id
   and g.item_id = w.item_id
   and exists( select 1
                 from Wishlist w1
                    , Giveaways g1
                where g1.person_id = p.person_id
                  and g1.item_id   = w1.item_id
                  and w1.person_id = g.person_id )

答案 2 :(得分:0)

select
      AllGiveWish.WhichWay,
      AllGiveWish.Item_ID,
      p1.Name as MainPersonName,
      p2.Name as OtherPersonName
   from
      ( select   
              "Give" as WhichWay,
              G.Item_ID,
              G.Person_ID as MainPerson,
              W.Person_ID as OtherPerson
           from
              GiveAways G
                 JOIN WishList W
                    on G.Item_ID = W.Item_ID
           where
              G.Person_ID = YourSinglePersonParm 
        UNION ALL
        select   
              "Wish" as WhichWay,
              W.Item_ID,
              W.Person_ID as MainPerson,
              G.Person_ID as OtherPerson
           from
              WishList W
                 JOIN GiveAways G
                    on W.Item_ID = G.Item_ID
           where
              W.Person_ID = YourSinglePersonParm ) As AllGiveWish

      join People P1
            on AllGiveWish.MainPerson = P1.Person_ID

      join People P2
            on AllGiveWish.OtherPerson = P2.Person_ID