简体   繁体   English

将一列联接到另一张表

[英]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 . 我有两个表, accountsorders 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 IDDateTotalStatus ,以及从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.

相关问题 将列从一个表连接到另一个表CodeIgniter中的另一列 - Join column from one table to another column in other table CodeIgniter 连接同一数据库中另一表的一个完整表和一列,并使用 PHP 显示 - Join one complete table and one column from another table inside the same database and display with PHP 连接表,其中一个表中的字段值是另一表中的列名 - Join table where field value in one table is a column name in another table Codeigniter-MySql:将一个表的三个列值与另一个表的ID连接起来 - Codeigniter - MySql : Join three column values of one table with the ID of another table 如何将一个表中的两个或更多列与另一个表中的一个列联接在一起,即使第一个表列中的值为NULL - How to join two or more columns from one table with one column from another table, even there are NULL values in first table columns PHP连接两个表,其中一个表中的两列包含from_ID和to_ID引用另一表中的id - PHP join two table where two column in one table contains from_ID and to_ID refer to id in another table 将一个结果集与另一张表zf2连接 - Join one resultset with another table zf2 从其他表连接一列并回显它 - Join One Column From other Table and Echo it 如何将两个表列与一个表联接? - How to join two table column with one? 将一列指向另一张表中的列 - Pointing one column to a column in another table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM