How do I establish a SQL query for this many-to-many table?

允我心安 提交于 2019-12-11 04:54:01

问题


I'm building this bartering-type function in this site using PHP/MySQL and I'm trying to create a query that responds with the following fields: owner's username, title, offerer's username, offerer's item

Basically I have three tables here with the following fields:

users

user_id, username, email 

items_available

item_number, owner_id (foreign key that links to user_id), title

offers_open

trade_id, offerers_id (fk of user_id), offerers_item(fk with item_number), receivers_id (fk from user_id)

How do I do this? I've seen some references to many-to-many SQL queries but they don't seem to particularly fit what I'm looking for (for example, the offerers_id and the owner_ids refer to different users_id in the Users table, but how do I make them distinguishable in the sql query?)


回答1:


If I understand correctly, this is what you are looking for:

SELECT owner.username, oferrers.username, ia.title
FROM offers_open o
  INNER JOIN users AS offerers
    ON o.offerers_id = offerers.user_id
  INNER JOIN items_available AS ia
    ON o.offerers_item= ia.item_number
  INNER JOIN users AS owner
    ON ia.owner_id = owner.user_id

I don't see a title on the users table, so didn't include one.




回答2:


I'm not sure exactly what output you want, but since your users table will appear twice in the query, they need to be aliased like so:

SELECT offerer.username AS offerer_username, title, receiver.username AS receiver_username
FROM users AS owner
JOIN items_available ON owner_id = owner.user_id
JOIN offers_open ON offerers_item = item_number
JOIN users AS receiver ON receivers_id

Again, don't know if that's what you want, but hope you get the idea.




回答3:


It sounds as you need an alias of the users table.

Something like?

select 
  u.*, ia.*, oo.*,u2.*
from
  users as u,
  items_available as ia,
  offers_open as oo,
  users as u2
where
  u.user_id = ia_user_id and
  oo.user_id = u2.user_id and
  oo.item_id = ia.item_id


来源:https://stackoverflow.com/questions/12710479/how-do-i-establish-a-sql-query-for-this-many-to-many-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!