Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query to match sellers and buyers

Tags:

sql

mysql

Okay so i got one table with people. One table with items that are given away and one with items people want.

People:
Person_ID, Name

Giveaways:
Person_ID, Item_ID

Wishlist:
Person_ID, Item_ID

So i want a query that returns exchange suggestions for a certain user.

So if i want exchange suggestions for person A it should return a list of people that are giving away an item that person A wants, and want an item that person A is giving away. The result should include: Person A's item, name of person too make exchange with as well as id and item_ID.

like image 891
LarsJK Avatar asked Jan 22 '26 10:01

LarsJK


1 Answers

@SérgioMichels' answer should be correct. But it doesn't get the seller's name, and it uses syntax that should (in my opinion) be avoided.

So, here is an alternative...

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 = ?
like image 83
MatBailie Avatar answered Jan 25 '26 03:01

MatBailie