我有两个用户ID链接的表。我想从两者中创建一个新表,从每个表中提取几个字段。在一个表中,每个用户ID只有一行,而另一个表中每个用户都有几行数据。
第一个表格很简单 - 所有数据都在一行中 但是,在第二个表中,数据按行排列,其中每个用户ID有几行。我想为每个用户ID找到这些行中的四个,然后将它们插入到我的表中的一列中。这是下面的代码,但它不起作用。我可以像这样嵌套子查询吗?
INSERT INTO new_table
select table1.ID, table1.user_email, table1.display_name, table2.meta-value (where table2.meta_key = ‘pet’), table2.meta-value (where table2.meta_key = ‘color'), table2.meta-value (where table2.meta_key = ‘location), table2.meta-value (where table2.meta_key = ‘house'),
from table_1, table2
答案 0 :(得分:1)
试试这个:
INSERT INTO new_table
(SELECT
t1.ID,
t1.user_email,
t1.display_name,
(SELECT meta-value FROM table2 AS t2 WHERE t2.meta_key = 'pet' AND t2.user_id = t1.user_id),
(SELECT meta-value FROM table2 AS t2 WHERE t2.meta_key = 'color' AND t2.user_id = t1.user_id),
(SELECT meta-value FROM table2 AS t2 WHERE t2.meta_key = 'location' AND t2.user_id = t1.user_id),
(SELECT meta-value FROM table2 AS t2 WHERE t2.meta_key = 'house' AND t2.user_id = t1.user_id),
FROM table_1 AS t1
)
然而,由于我没有找到有关表架构/数据的更多详细信息,因此未对其进行测试。希望这会有所帮助。
答案 1 :(得分:1)
您可以使用查询加入:
ExamplePageAdapter examplePageAdapter = new ExamplePageAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(examplePageAdapter);
答案 2 :(得分:1)
INSERT INTO new_table
select table1.ID, table1.user_email, table1.display_name,
max(if(table2.meta_key = 'pet', table2.meta-value, NULL)),
max(if(table2.meta_key = 'color', table2.meta-value, NULL)),
max(if(table2.meta_key = 'location', table2.meta-value, NULL)),
max(if(table2.meta_key = 'house', table2.meta-value, NULL))
from table1
left join table2 on table2.user_id=table1.user_id
group by table1.ID, table1.user_email, table1.display_name
答案 3 :(得分:0)
我得到了它的工作。我不知道这是否比任何其他建议更好或更差。
INSERT INTO new_table
SELECT t1.ID, t1.user_email, t1.display_name,
GROUP_CONCAT(IF(m.meta_key = 'pet_field', m.meta_value, NULL)) AS pet,
GROUP_CONCAT(IF(m.meta_key = 'color_field', m.meta_value, NULL)) AS color,
GROUP_CONCAT(IF(m.meta_key = 'location_field', m.meta_value, NULL)) AS location,
GROUP_CONCAT(IF(m.meta_key = 'house_field', m.meta_value, NULL)) AS house
FROM wp_users t1,
wp_usermeta m
WHERE u.ID = m.user_id
GROUP BY u.ID;