使用连接查询中的数据创建列

时间:2018-03-29 19:37:36

标签: sql join group-by sql-update alter-table

我有两张桌子,

一件有物品:

ic_items

 item_id  name                description 

      1   Pepperino           Hot sauce from Argentina
      2   Vamos el Couchiero  Hot sauce from Spain  

一票赞成:(火焰= 1票)

ic_flames

  flame_id  item_id

     1         1
     2         1
     3         2

现在我想连接它们。所以像这样的东西加入第一个表:

  item_id  name               description                 flame_counter

      1   Pepperino           Hot sauce from Argentina         2
      2   Vamos el Couchiero  Hot sauce from Spain             1

我使用此查询:

SELECT ic_items.item_id, COUNT(ic_flames.flame_id) AS flame_counter
FROM ic_flames 
JOIN ic_items ON ic_items.item_id=ic_flames.item_id
GROUP BY ic_items.item_id

当我在phpmyadmin上填写这个查询时,我得到一个带有flame_counter的表,但是当我去ic_items时,我没有看到flame_counter。

如何将flame_counter放入我的ic_items表?

2 个答案:

答案 0 :(得分:0)

您可以使用子查询来计算ic_flames中具有当前item_id的表条目。虽然为每次投票实施反ic_flames而不是新行的反击也会更好。这是一个未经测试的例子。希望它有所帮助;)

SELECT   ic_items.item_id, 
         ic_items.name, 
         ic_items.description,
         (
         SELECT   COUNT(*) 
         FROM     ic_flames AS sub_ic_flames
         WHERE    sub_ic_flames.item_id = ic_items.item_id
         GROUP    BY sub_ic_flames.item_id
         ) AS flame_counter
FROM     ic_items

// EDIT

要更新表ic_items中的flame_counter,请使用以下查询。

UPDATE   ic_items
SET      flame_counter = (
             SELECT   COUNT(*) 
             FROM     ic_flames AS sub_ic_flames
             WHERE    sub_ic_flames.item_id = ic_items.item_id
             GROUP    BY sub_ic_flames.item_id
         )

答案 1 :(得分:0)

这里的选择就是这样,选择。如果要将它们添加到现有表中的现有项目,这是UPDATE statement,如果要为这些值创建新列,则需要ALTER TABLE statement。在你的情况下,alter table需要先来,你需要combine your JOIN with an UPDATE,它看起来像这样:

ALTER TABLE table_name
ADD flame_counter int(250);

UPDATE ic_items
SET flame_counter = COUNT(flames.flame_counter)
FROM (
    SELECT ic_items.item_id, COUNT(ic_flames.flame_id) AS flame_counter
        FROM ic_flames 
    JOIN ic_items ON ic_items.item_id=ic_flames.item_id
    GROUP BY ic_items.item_id
) AS flames;