我正在使用PHP / MySQL在此站点中构建此易货类型函数,并且我正在尝试创建一个响应以下字段的查询: 所有者的用户名,标题,提供者的用户名,提供者的项目
基本上我在这里有三个表,其中包含以下字段:
用户
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)
我该怎么做?我已经看到一些对多对多SQL查询的引用,但它们似乎并不特别适合我正在寻找的东西(例如,offerers_id和owner_ids引用Users表中的不同users_id,但是怎么做我在sql查询中区分它们吗?)
答案 0 :(得分:4)
如果我理解正确,这就是你要找的东西:
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
我在users
表格上看不到标题,因此没有包含一个标题。
答案 1 :(得分:0)
我不确定您想要什么输出,但由于您的users
表在查询中会出现两次,因此需要将其设置为别名:
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
再一次,不知道这是不是你想要的,但希望你明白这一点。
答案 2 :(得分:0)
听起来你需要用户表的别名。
喜欢什么?
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