[英]Join in one column to another table
I know this question is very common on Stack, but I can't seem to find an answer or a snippet of code that actually solves my problem... 我知道这个问题在Stack上很常见,但是我似乎找不到真正解决我问题的答案或代码片段...
I have two tables, accounts
and orders
. 我有两个表,
accounts
和orders
。 I want to write a SQL statement to pull Order ID
, Date
, Total
and Status
from orders
, and also Username
from accounts
. 我想编写一条SQL语句从
orders
提取Order ID
, Date
, Total
和Status
,以及从accounts
提取Username
。
The statement would be something like this: 该语句将是这样的:
$ohsql = "select * from orders where Username = '". $login_session ."'";
Obviously Username
will come from the accounts
table, but the principal is there. 显然,
Username
来自accounts
表,但是主体在那里。 I am missing the join
as I am clueless about it! 我缺少的
join
,因为我无能了!
You need to 'link' the two tables. 您需要“链接”这两个表。 For that do something like :
为此,请执行以下操作:
- add a column accountid
to Orders table; -在“订单”表中添加一列
accountid
; so this tells us, which order belongs to which user . 所以这告诉我们,哪个订单属于哪个用户。 We then use this info in our JOIN.
然后,我们在JOIN中使用此信息。
Easy way to do it in 2 queries : 在2个查询中执行此操作的简单方法:
// get the id value of the username
$id = select id from accounts table where username = $login_session
// use that in the JOIN
select * from orders JOIN accounts ON orders.accountid = accounts.id where accounts.id = $id
Assuming that your orders table contains the accountId and your accounts table containing the user name use following query 假设您的订单表包含accountId,而您的帐户表包含用户名,则使用以下查询
$ohsql = "select o.*, a.username from orders o
INNER JOIN accounts a ON a.id = o.accountId
WHERE a.username = '". $login_session ."'";
Let me know if you face any issue 让我知道您是否遇到任何问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.