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

Create a column with data from a join query

我有两个table,

一个有物品:

ic_items

 item_id  name                description 

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

有票数:(flame = 1 票)

ic_flames

  flame_id  item_id

     1         1
     2         1
     3         2

现在我想连接它们。所以像这样的事情正在加入第一个table:

  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 的 table,但是当我转到 ic_items 时,我没有看到 flame_counter .

如何将 flame_counter 放入我的 ic_items table?

您可以执行一个子查询来计算 ic_flames 中的 table-entries,当前 item_id。尽管将 counter-entry 实现为 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

//编辑

要在 table 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
         )

这里的 selection 就是这样做的,select。如果您想将它们添加到现有 table 中的现有项目,即 UPDATE statement, and if you want to create a new column for those values, you need an ALTER TABLE statement. In your case, the alter table needs to come first, and you will need to 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;