尝试在一个查询中提取两组不同的数据

时间:2015-09-29 00:57:55

标签: mysql

我有三个表将涉及一个查询。这是查询尝试执行的操作:

玩家创建交易要约。交易提供表结构是这样的:

id              int(11)
sender          int(11)
receiver        int(11)
offer           text
request         text
active          tinyint(1)
slot_upgrade    int(11)

当玩家创建交易要约时,他们发送交易的城市的ID存储在sender字段中,目标城市的ID 他们发送的交易存储在receiver字段中。

现在,当玩家登录时,我想提取所有活跃的交易。

我有这样的事情:

SELECT ct.id, ct.offer, ct.request, cities.name, cities.userid, cities.x, cities.y,users.username
    FROM cities_trades AS ct
        LEFT JOIN cities ON ct.sender = cities.id
        LEFT JOIN users ON cities.id = users.id
    WHERE ct.active = 1 AND (ct.sender IN (1,2) OR ct.receiver IN (1,2))

此查询会在active tinyint(1)表中找到所有活动的(活动意味着cities_trades字段设置为1)进行交易。

它还会使用userid表中的LEFT JOIN字段在cities表上执行sender来提取发件人的cities_trades citiescities表中的城市ID相关联。

通过这样做,我可以从交易创建者的users表和receiver表中提取任何信息,或者在这种情况下,发件人

但是,如果我还要提取有关sender的所有相同信息,而不仅仅是cities_trades(我想要两者都有相关信息),我该怎么办呢?

我能想到的唯一其他解决方案是通过在sender_player_id表中添加两个新字段来存储他们的相对玩家ID(例如,而不仅仅是他们的城市ID)来简化查询。

receiver_player_id python

我希望这个问题有道理。感谢。

1 个答案:

答案 0 :(得分:1)

您实际上可以针对cities表执行两个联接,一个用于交易交易的每一方。为cities_sendercities_receiver(或类似)使用不同的别名。然后,您可以在SELECT

中列出所有内容
SELECT 
  ct.id,
  ct.offer, 
  ct.request,
  -- Specify all sender columns with an alias
  cities_sender.name AS sender_name,
  cities_sender.userid AS sender_userid,
  cities_sender.x AS sender_x,
  cities_sender.y AS sender_y,
  -- Then specify all receiver columns with a different alias
  cities_receiver.name AS receiver_name,
  cities_receiver.userid AS receiver_userid,
  cities_receiver.x AS receiver_x,
  cities_receiver.y AS receiver_y,
  -- Also for usernames on both sides of the relationship
  users_sender.username AS sender_username,
  users_receiver.username AS receiver_username
FROM
  cities_trades AS ct
  -- Join once for the sender side
  LEFT JOIN cities AS cities_sender ON ct.sender = cities_sender.id
  -- Join again for the receiver side
  LEFT JOIN cities AS cities_receiver ON ct.receiver = cities_receiver.id
  -- Likewise, for users
  LEFT JOIN users users_sender ON cities_sender.id = users_sender.id
  LEFT JOIN users users_receiver ON cities_receiver.id = users_receiver.id
WHERE
   ct.active = 1
   AND (ct.sender IN (1,2) OR ct.receiver IN (1,2))

编辑:为用户名添加了发件人/收件人加入......