MySQL使用pivot插入两个单独的表

时间:2013-11-29 00:53:36

标签: mysql joomla

从.csv

引入的单个表(user_import)开始
| Name       | Login | Email                | CustomA | CustomB |
+------------+-------+----------------------+---------+---------+
| John Smith | johns | john_smith@gmail.com | Blarg   | Narx    |
| Max Power  | maxp  | max_power@gmail.com  | Jarg    | Lipdo   |
+------------+-------+----------------------+---------+---------+

尝试让它填充Joomla!用户表

| id  | name       | username | email                | ...
| 514 | Super User | admin    | admin@gmail.com      | ...
| 515 | John Smith | johns    | john_smith@gmail.com | ...
| 516 | Max Power  | maxp     | max_power@gmail.com  | ...

并将任何自定义自定义字段插入user_profiles表

+---------+-------------------------------------+---------------+----------+
| user_id | profile_key                         | profile_value | ordering |
+---------+-------------------------------------+---------------+----------+
|     515 | customprofile.custom_a              | "Blarg"       |        1 |
|     515 | customprofile.custom_b              | "Jarg"        |        2 |
|     516 | customprofile.custom_a              | "Narx"        |        1 |
|     516 | customprofile.custom_b              | "Lipdo"       |        2 |
+---------+-------------------------------------+---------------+----------+

我不认为有一种方法可以在一次调用中执行此操作,因为user_id必须auto_increment

第一个问题是相当严格的前进

INSERT INTO prknc_users (name, username, email, params, password)
SELECT Name, Login, Email, '{}', 'tuChaSw-tEte72_!eSW#muc3@trew8steZacra2e7a7R6yuqAyeSAXUy=Stu'
FROM user_import;`

第二个是我需要一些帮助的人,尝试用这个:

INSERT INTO user_profiles (user_id, profile_key, profile_value, ordering)
SELECT (SELECT users.id FROM users, user_import WHERE users.email = user_import.Email), 'customprofile.custom_a',user_import.CustomA, '1'
FROM user_import;

失败了。如果可以,请帮帮我。

3 个答案:

答案 0 :(得分:1)

您可以尝试这样的应用程序

https://gist.github.com/elinw/5b579e18b9613f08330d

只需确保在您的用例中进行有意义的更改。

答案 1 :(得分:0)

内部选择可以返回多个值,而不与外部选择中的其他列同步。您应该将最后三列移动到第一个选择中。

INSERT INTO user_profiles (user_id, profile_key, profile_value, ordering)
(SELECT users.id, 'customprofile.custom_a',user_import.CustomA, '1' 
    FROM users, user_import 
    WHERE users.email = user_import.Email)

答案 2 :(得分:0)

INSERT INTO user_profiles (user_id, profile_key, profile_value, ordering)
  SELECT users.id,'customprofile.custom_b',user_import.CustomB, '2'
    FROM users, user_import 
    WHERE users.email = user_import.Email
UNION
  SELECT users.id,'customprofile.custom_a',user_import.CustomA, '1'
  FROM users, user_import
  WHERE users.email = user_import.Email;