[英]Php mysql Query two usernames in one row based on id from another table
I am somewhat new to coding and have been trying to write what I thought would be a straightforward sql query. 我对编码有点陌生,一直在尝试编写我认为会很简单的sql查询的内容。 Please help :)
请帮忙 :)
Table 1: Users
id = user idt
username = user name
Table 2: Orders
orderid = order id
order_to = user id of person buying
order_from = user id of person selling
oder_details = text
Basically I want to: 基本上我想:
"Select Username(from), Username(to), order_details FROM mytables WHERE Order id = 1;"
And get the result as 1 row, I'm not sure how to proceed. 并将结果作为1行,我不确定如何继续。 I thought I could do this with concatenation or something... Can anyone help?
我以为可以通过串联或其他方式执行此操作...有人可以帮忙吗?
You need to use JOIN
to link the tables together. 您需要使用
JOIN
将表链接在一起。
SELECT fu.username AS fromUser, tu.username AS toUser, o.order_details
FROM Orders o
INNER JOIN Users fu
ON fu.id = o.order_to
INNER JOIN Users tu
ON tu.id = o.order_from
WHERE o.orderid = '1';
Because you have two different users that you need the username from, you need to JOIN
the Users table twice to get both user's usernames. 因为您有两个不同的用户需要用户名,所以您需要两次
JOIN
Users表以获取两个用户的用户名。 Each table needs to have it's own alias fu
and tu
to allow MySQL to differentiate between them. 每个表都必须具有自己的别名
fu
和tu
,以便MySQL区分它们。 The same goes for the column names in your SELECT
statement so that when you fetch the results with PHP, php can differentiate between the two usernames. SELECT
语句中的列名也是如此,因此,当您使用PHP获取结果时,php可以区分两个用户名。
You are looking for a JOIN
. 您正在寻找
JOIN
。 This can be done with a keyword or through WHERE
clauses. 可以使用关键字或通过
WHERE
子句来完成。 For example, 例如,
SELECT * FROM Orders JOIN Users ON Orders.order_to=Users.id
The documentation can be found here: http://dev.mysql.com/doc/refman/5.0/en/join.html . 该文档可以在这里找到: http : //dev.mysql.com/doc/refman/5.0/en/join.html 。
I'll leave it as an exercise to figure out how to JOIN
the order_from
. 我将把它作为练习来弄清楚如何
JOIN
order_from
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.