带有动态列名的MySQL Query

时间:2015-03-24 18:00:15

标签: mysql

我有一个包含这些列的源表:

enter image description here

我还有一个这样的目标表:

enter image description here

目标表有1440行,其中填充了分钟列(当天每分钟有1行)。

对于源表中的每一行,我需要填写一个" 1"在目标表中为适当的通道(总共有10个通道),在StartTime和FinishTime之间的每一分钟。

我只是在MySQL Workbench中这样做(这是一次性查询)。我的野兽方法是什么?

谢谢,

-Scott

3 个答案:

答案 0 :(得分:1)

的伪代码:

SELECT DISTINCT ChannelNumber
FROM source

while ($row = fetch_assoc()) {
    $channel_col = 'ch'.$row['ChannelNumber']
    $sql =  "
        UPDATE destination
        JOIN source ON StartTime = destination.minutes 
             AND source.ChannelNumber = $row[ChannelNumber]
        SET destination.$channel_col = 1
      ";
    query($sql);
}

通常,您必须关注动态创建一个字符串,该字符串将成为SQL查询以避免SQL注入,但由于所有数据都来自数据库,因此不应该成为问题。

答案 1 :(得分:0)

这是一个MySQL解决方案:

CREATE PROCEDURE PopulateDestinationTable()
BEGIN
DECLARE i INT DEFAULT 0;
DECLARE n INT DEFAULT 0;
DECLARE CNumber INT DEFAULT 0;
DECLARE STime INT DEFAULT 0;
DECLARE FTime INT DEFAULT 0;

SELECT COUNT(*) FROM SourceTable INTO n;
SET i = 0;

WHILE i < n DO
    SELECT ChanelNumber FROM SourceTable LIMIT i, 1 INTO CNumber;
    SELECT StartTime FROM SourceTable LIMIT i, 1 INTO STime;
    SELECT FinishTime FROM SourceTable LIMIT i, 1 INTO FTime;

   SET @stat1 = CONCAT('UPDATE DestinationTable
                SET ', CONCAT('Ch', CNumber), ' = 1 WHERE minutes BETWEEN ? AND ?');

    PREPARE statement FROM @stat1;
    SET @p1 = STime;
    SET @p2 = FTime;
    EXECUTE statement USING @p1, @p2;

    SET i = i + 1;
END WHILE;
END$$

P.S。在创建存储过程时不要忘记更改分隔符:)

答案 2 :(得分:0)

我将@ peter-bowers中的PHP代码修改为此代码并使其工作:

<?php

$mysqli = new mysqli("ip", "user", "pass", "db");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";

$res = $mysqli->query("update scott_test set Ch1 = null, Ch2 = null, Ch3 = null, Ch4 = null, Ch5 = null, Ch6 = null, Ch7 = null, Ch8 = null, Ch9 = null, Ch10 = null");

$res = $mysqli->query("SELECT TIMESTAMPDIFF(MINUTE,DATE(TimeReceived),TimeReceived) AS StartTime, 
                CEIL(FaxDuration/60)+ TIMESTAMPDIFF(MINUTE,DATE(TimeReceived),TimeReceived) AS FinishTime,
                ChannelNumber
        FROM
                fax_received
        WHERE
                DATE(TimeReceived) = DATE((NOW() - INTERVAL 3 DAY))");

while ($row = $res->fetch_assoc()) {

    $channel_col = 'ch'.$row['ChannelNumber'];
    $start_min = $row['StartTime'];
    $end_min = $row['FinishTime']; 
    $sql =  "UPDATE scott_test
                SET $channel_col = 1          
                WHERE minutes between ($start_min, $end_min);
    $mysqli->query($sql);

}
?>