如何在插入时检查表是否在MySQL中使用php记录?

时间:2017-12-01 12:25:17

标签: php mysql rows

我使用以下代码处理'text files'。在这里我说如果'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''当我将数据存储到MySQL时,我该怎么做?

    $sajUsers = file_get_contents( 'users.txt' );
    $ajUsers = json_decode($sajUsers);

    // Create the JSON ONBJECT with key values
    if ( count( $ajUsers ) === 0 ) { // if the aray is empty create an Admin
    //echo( "The array is empty creating admin" );
    $jNewUser->role = 'admin';
    }  else { // if it´s not empty create a user
    //echo( "The array isnt empty creating user" );
    $jNewUser->role = 'user';
    }

1 个答案:

答案 0 :(得分:0)

# what I would like to obtain:
#_timeslice              _count     _min_val1   _avg_val1   _max_val1   _first_val2  _last_val2
# 2017-11-01T00:00:00Z     4          90          100         110          200        210
# 2017-11-01T00:15:00Z     3         100          110         120          240        230
# 2017-11-01T00:30:00Z     2         110          120         130          270        265
# 2017-11-01T00:45:00Z     4          80          112.5       150          290        320

CREATE TABLE `test-table`
    (`date_time` datetime, `val1` float, `val2` float);

INSERT INTO `test-table`
    (`date_time`,         `val1`, `val2`)
VALUES

    ('2017-11-01 00:00:00', 100,   200),  # first 15 min
    ('2017-11-01 00:01:00', 110,   190),
    ('2017-11-01 00:02:05',  90,   220),
    ('2017-11-01 00:14:00', 100,   210),

    ('2017-11-01 00:15:00', 100,   240),  # second 15 min
    ('2017-11-01 00:16:00', 110,   250),
    ('2017-11-01 00:28:00', 120,   230),

    ('2017-11-01 00:30:00', 110,   270),  # third 15 min
    ('2017-11-01 00:44:59', 130,   265),

    ('2017-11-01 00:50:00', 120,   290),  # fourth 15 min 
    ('2017-11-01 00:55:00', 150,   300),
    ('2017-11-01 00:57:00', 100,   280),
    ('2017-11-01 00:58:00',  80,   320)
;

SELECT FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(`date_time`)/900)*900) AS _timeslice,
    COUNT(*) AS _count,
    min(`val1`) as _min_val1,
    avg(`val1`) as _avg_val1,
    max(`val1`) as _max_val1,
    coalesce(`val2`) as _first_val2  # returns the first val2 in the group
    # ----> how to add here the last val2 for the group?
FROM `test-table`
GROUP BY _timeslice;