Mysql从表中选择多个id并将它们插入另一个表中

时间:2011-08-20 16:29:31

标签: php mysql joomla

我有一个名为

的mysql表
jos_users_quizzes with the following columns:

id
quiz_i
duser_id

I have a second table called  jos_users with this columns
id
name
username
department

第一个表上的user_id与第二个表的id链接,因此quiz_id = id(jos_users) 如何构建查询以多个插入所选部门的ID到jos_users_quizzes表...单击一下

我在想一个子查询或循环会做,但不知道如何构建查询。  我需要从所选部门中选择所有用户ID。例如,有一个部门列表,一旦选择了部门,选择所有与该部门相关的ID并将所有ID插入另一个表中(quizid,(alldepartment ids)

提前致谢!

代码来自和ASP.NET表单插入....

  string quizidselected = DropDownList1.SelectedValue;
            string deptselected = ListBox2.SelectedValue;
            //OdbcCommand cmd = new OdbcCommand("INSERT INTO jos_jquarks_users_quizzes  (quiz_id,user_id) VALUES (' " + quizidselected + " ',677)");
            OdbcCommand cmd = new OdbcCommand("INSERT INTO jos_jquarks_users_quizzes (user_id, quiz_id)    SELECT id, ' " + quizidselected + " ' FROM jos_users  WHERE department = ' " + deptselected + " '"); 

3 个答案:

答案 0 :(得分:1)

根据我对你想要的解释......

INSERT INTO jos_users_quizzes (user_id, quiz_id)
    SELECT id, :new_quiz_id
        FROM jos_users
        WHERE department = :department

答案 1 :(得分:0)

如果您使用自动增量设置ID,那么您可以执行类似这样的操作

insert into jos_users_quizzes (quiz_i) select id from jos_users;

答案 2 :(得分:0)

如果您知道电子邮件地址,部门ID或部门名称等关键字,那么很容易。

例如:

$depname = "Logistics"; // PHP // department name
$quizid = "Quiz-12"; // PHP // quiz name

然后进行插入查询:

<?php 
$query = "INSERT INTO `to_table` (user_id, quiz_id) 
                 SELECT id, '$quizid' FROM `from_table` 
                 WHERE department = '$depname'"; 
?>

为了获得更多兼容性,如果您从网页获取值,则可以使用小写,例如:

<?php 
$query = "INSERT INTO `to_table` (user_id, quiz_id) 
                 SELECT id, LOWER('%$quizid%') 
                 FROM `from_table` 
                 WHERE department like LOWER('%$depname%')"; 
?>

使用addslashes命令在从网页插入数据时保护数据库:

<?php 
$query = "INSERT INTO `to_table` (user_id, quiz_id) 
                 SELECT id, LOWER('%".addslashes($quizid)."%') 
                 FROM `from_table` 
                 WHERE department like LOWER('%".addslashes($depname)."%')"; 
?>