简体   繁体   English

SQL合并两个表中的数据

[英]SQL combining data from two tables

I have two tables... 我有两张桌子

+-----------+-----------+
| employees | positions |
+-----------+-----------+
| id        | id        |
| fname     | pos       |
| lname     |           |
| hphone    |           |
| cphone    |           |
| email     |           |
| posid     |           |
+-----------+-----------+

I want to create a form to add a new employee and have a dropdown for the position so that you pick from a position that is listed in the positions table 我想创建一个表单以添加新员工并对该职位进行下拉,以便您从职位表中列出的职位中进行选择

I know how to make the dropdown box but i am not sure how to setup the sql and how to save it as a new record...can someone please help me? 我知道如何制作下拉框,但是我不确定如何设置sql以及如何将其保存为新记录...有人可以帮助我吗?

The code im using for the dropdown is a function called getpos and it is... 我用于下拉菜单的代码是一个名为getpos的函数,它是...

function getpos(){
$sql=mysql_query("SELECT id,pos FROM positions"); 
if(mysql_num_rows($sql)){ 
$select= '<select name="select">';   
while($rs=mysql_fetch_array($sql)){ 
  $select.='<option value="'.$rs['id'].'">'.$rs['pos'].'</option>'; 
  } 
} 
$select.='</select>'; 
echo $select;
}

it works fine...to call it i use 它工作正常...我称之为

this is the SQL i thought about...is it correct? 这是我考虑过的SQL ...正确吗?

SELECT employees.id, employees.fname, employees.lname, employees.hphone,
employees.cphone, employees.email, employees.posid
FROM employees
INNER JOIN
positions ON positions.posid = employees.posid 

Use: 采用:

SELECT id, pos FROM positions ORDER BY pos DESC; 

to populate the the drop down list. 来填充下拉列表。 The positions will be given in descending order. 职位将按降序排列。

I don't know which method you using for the form action (GET/POST). 我不知道您要使用哪种方法进行表单操作(GET / POST)。 But on the next page you will retrieve $_GET['id'] or $_POST['id'] and insert that into your other table employees (posid). 但是在下一页上,您将检索$_GET['id']$_POST['id']并将其插入到其他表employee(posid)中。

Then you use the values from your form to insert into you database. 然后,使用表单中的值将其插入数据库。

INSERT INTO (fname, flname, hphone,cphone,email, posid 
FROM employees 
VALUES (....values from the form ...); 

One of the variable you want to insert is the ID from positions. 您要插入的变量之一是位置ID。

If you want to SELECT the data from the database in order to display them in a table for instance you could use this query: 如果要从数据库中选择数据以便例如在表中显示它们,可以使用以下查询:

SELECT position.name, employees.fname, employees.flname,
employees.hphone, employees.cphone,employees.email 
FROM employees JOIN positions 
ON employees.posid = posistion.id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM