I have a table has 4 fields columns; id, cinema_id, movie_id, showing_at.
id - Integer(primary key)
cinema_id - Integer(foreign key)
movie_id - Integer(foreign key)
showing_at - Datetime
Am trying to come up with a query that retrieves the result from table based on the movie_id column and a date, and groups the results using the cinema_id;
My current query looks like this using laravel
$models = DB::table('showtimes')->where('movie_id', $movie_id)
->whereBetween('showing_at', [$date." 00:00", $date." 23:00"])
->groupBy('cinema_id')
->get();
The dumped query result looks like this
Array
(
[0] => stdClass Object
(
[id] => 161
[cinema_id] => 1
[movie_id] => 15
[showing_at] => 2016-03-20 12:20:00
[created_at] =>
[updated_at] =>
)
[1] => stdClass Object
(
[id] => 145
[cinema_id] => 3
[movie_id] => 15
[showing_at] => 2016-03-20 10:00:00
[created_at] =>
[updated_at] =>
)
)
How do i query the db to group all the showtimes under cinema_id
Related
I have JSON which need to insert into MySQL table.
What I already did is, convert it to array using:
$json_data = json_decode($geo_json, true);
and get an output of array but I do not know how to inset into second and third MySQL table.
My MySQL Table:
Table 1:
geo_id | user_id | geo_title | geo_description | geo_date |geo_status |geo_action |action_reason | geo_json | remote_ip | map_type |geo_snapshot
I can able to insert into above table easily but problem is in table two and Three listed below.
Table 2:
id | layer_id | map_id | layer_name | user_id | draw_type | latlng | radious
Table 3:
data_id | geo_key | geo_value | map_id | layer_id
Array I am getting:
Array
(
[type] => FeatureCollection
[features] => Array
(
[0] => Array
(
[type] => Feature
[properties] => Array
(
[action] => a
[poi_name] => a
[fac_type] => 17
[ph_number] => a
[hno] => a
[postcode] => a
[mail] => a
[str_nm] => a
[photo] => developer-page.png
[comment] => a
[url] => a
[sub_loc] => a
[employee] => a
)
[geometry] => Array
(
[type] => Point
[coordinates] => Array
(
[0] => 88.434448242188
[1] => 22.510971144638
)
)
)
[1] => Array
(
[type] => Feature
[properties] => Array
(
[action] => b
[poi_name] => b
[fac_type] => 18
[ph_number] => b
[hno] => b
[postcode] => b
[mail] => b
[str_nm] => b
[photo] => 1475131600_developer-page.png
[comment] => b
[url] => b
[sub_loc] => b
[employee] => b
)
[geometry] => Array
(
[type] => Point
[coordinates] => Array
(
[0] => 88.321151733398
[1] => 22.50906814933
)
)
)
)
)
Now problem is to insert above data into two separate tables:
Table 2: This is only require to insert draw_type | latlng from above php array.
Example: draw_ type: point and latlng : coordinates
Table 3:
This is require to insert geo_key | geo_value | map_id | layer_id from above PHP array.
Example:
geo_key : properties [action,poi_name,fac_type,ph_number,hno,postcode,mail,str_nm, photo, comment, url, sub_loc, employee]
geo_value : [properties values ]
map_id :[this will be table 1 insert id]
layer_id : [this can be blank]
Please guide me and show me how to start.
$json_data["features"][$array_index]["geometry"]["type"]
For table2:
foreach($json_data["features"] as $info){
$type = $info["geometry"]["type"];
$latlng_0 = $info["geometry"]["coordinates"][0];
$latlng_1 = $info["geometry"]["coordinates"][1];
// DO INSRET with $type, $latling_0, $latling_1
$sql = "INSERT INTO Table2 (draw_type, latlng0, latlng1) VALUES ('".$type."','".$latlng_0."','".$latlng_1."')";
....
}
For table3:
Is 'map_id' a auto increment key in table1?
You'll need to know map_id first by select * where (conditions)
after successful insert data to table1
And if 'layer_id' can accept blank (null) data, it'll be fine if you don't specific value in INSERT command. Just make sure your table have correct settings.
I have a database for clock in clock out system The table structure consists of time_id, user_id, weekNo, ClockYear, EntryDate, StartTime, EndTime and updated_at
basically the startTime is clock in and EndTime is clocked out time what im trying to do is run a query to get me the total worked hours by a user on a sepcific date total instead of total hours worked per individual entry. so currently i have the following query:
SELECT CONCAT(users.first_name," ",users.last_name) AS theUser,
time_logs.*, TIMEDIFF(endTime,startTime) AS totTime FROM time_logs
LEFT JOIN users ON time_logs.user_id = users.user_id WHERE
time_logs.entryDate >= "2016-08-17" AND time_logs.entryDate <= "2016-08-25" order by user_id ASC
and this returns the results as
[0] => Array
(
[theUser] => Sam Johnson
[timeId] => 14
[user_id] => 1
[weekNo] => 34
[clockYear] => 2016
[entryDate] => 2016-08-23
[startTime] => 2016-08-23 16:16:30
[endTime] => 2016-08-23 17:36:14
[updated_at] => 2016-08-23 17:36:14
[totTime] => 01:19:44
)
[1] => Array
(
[theUser] => Sam Johnson
[timeId] => 15
[user_id] => 1
[weekNo] => 34
[clockYear] => 2016
[entryDate] => 2016-08-24
[startTime] => 2016-08-24 01:00:00
[endTime] => 2016-08-24 05:15:00
[updated_at] =>
[totTime] => 04:15:00
)
[3] => Array
(
[theUser] => Bob Doe
[timeId] => 19
[user_id] => 2
[weekNo] => 34
[clockYear] => 2016
[entryDate] => 2016-08-24
[startTime] => 2016-08-24 10:00:00
[endTime] => 2016-08-24 13:15:00
[updated_at] =>
[totTime] => 03:15:00
)
As you can see it gives total time for that specific entry but what i want to get is just one entry for each user with the total time totalled up for all entries by that user on that day combined so for user 1
[0] => Array
(
[theUser] => Sam Johnson
[user_id] => 1
[weekNo] => 34
[clockYear] => 2016
[entryDate] => 2016-08-23
[totTime] => 05:34:44
)
can anyone help with this not sure if i can do it using a query
You are almost there!
Assuming that totTime is a Time Field (Not a DateTime field) and I HOPE user_id is unique
Sorry I put XXX as I didn't want to spend the time writing this fully out
Select CONCAT(XXX) theUser, user_id,min(weekNo) weekNo,min(clockYear) clockYear, min(entryDate) entryDate,sum(TIMEDIFF(endTime,startTime)) totTime FROM XXX ORDER BY user_id GROUP BY user_id
That should give you what you want. The key is GROUP BY which you didn't have. You can change the MIN commands to MAX if that's what you want to show.
theUser will be picked from the last entry I believe, user_id should remain the same and the other fields will be calculated by the GROUP BY and I had to repeat the field names on the sum and min functions because sum and min return a unique fieldname
Get the results from follow table max(date)
leads table
id name
75943 name1
82501 name2
lead_follow_up
id lead_id msg date updated
1 75943 msg1 1438930800 1438884890
2 75943 msg2 1416459600 1415901523
3 82501 msg1 1454713200 1454485087
4 82501 msg1 1439362800 1438564891
using the following query i get result
$today_date = mktime(0, 0, 0, $mon, $day-1, $year);
SELECT * FROM (`lead_follow_up`) LEFT JOIN `leads` ON `leads`.`id` = `lead_follow_up`.`lead_id` WHERE `date` <= $today_date GROUP BY `lead_follow_up`.`lead_id` ORDER BY `lead_follow_up`.`date` DESC
from the above query i get array $previou
$previou= Array
(
[0] => stdClass Object
(
[id] => 1
[lead_id] => 75943
[date] => 1438930800
[updated_on] => 1438884890
)
[1] => stdClass Object
(
[id] => 2
[lead_id] => 75943
[date] => 1416459600
[updated_on] => 1415901523
),
[2] => stdClass Object
(
[id] => 3
[lead_id] => 75943
[date] => 1416459600
[updated_on] => 1415901523
),....etc
);
foreach($previou as $key => $p):
$q = "SELECT `id` FROM (`lead_follow_up`) WHERE `lead_id` = '".$p->id."' AND `date` > '".$p->date."' ORDER BY `updated_on` DESC ";
if(!$this->db->query($q)){
$previouData[$key] = $p;
$pCount++;
}
endforeach;
What I'm really expecting to see is data like
id lead_id name msg
1 75943 name1 msg1
any help to optimize this in single query
So, there's the User model, and the Item model. It's a many-to-many relation: an item can belong to many users, and a user can have many items. Therefore, there's the UserItemRel model.
To summarize:
item
id
name
date_created
date_updated
user
id
email
password
date_created
date_updated
user_item_rel
user_id
item_id
date_created
My query, before making the switch to Yii2, was this:
SELECT COUNT(UIR.`user_id`) as `favourited`, IT.`id`, IT.`name`, CA.`name` as `category`
FROM `user_item_rel` UIR
LEFT JOIN `item` IT ON UIR.`item_id` = IT.`id`
LEFT JOIN `category_item` CI ON UIR.`item_id` = CI.`item_id`
LEFT JOIN `category` CA ON CI.`category_id` = CA.`id`
WHERE UIR.`date_created` >= (SYSDATE() - INTERVAL 3 YEAR)
GROUP BY UIR.`item_id`
ORDER BY
`favourited` DESC
LIMIT 20
I've used the yii2-enhanced-gii extension to generate the models.
I want to show the 20 most favourited items in the past 48 hours, with their counts. I'm migrating from Yii1.1, and it's been quite the ride so far, and I can't figure this out.
I've found
$this->hasMany(UserItemRel::className(), ['id' => 'user_id'])
->viaTable('user_item_rel', ['id' => 'item_id'], function ($query) {
$query->andWhere(['date_created < INTERVAL 2 DAY'])
->orderBy(['COUNT(*)' => SORT_DESC]);
});
}
but how to properly use this?
The query would something like bellow. I would try to run a native query instead of trying to find out how this could be done withing the orm.
SELECT item_id, item.name, count(*) favorite
FROM user_item_rel
LEFT JOIN user ON user.id = user_item_rel.user_id
LEFT JOIN item ON item.id = user_item_rel.item_id
WHERE user_item_rel.date_created >= (sysdate() - interval 2 DAY)
GROUP BY item_id, name
ORDER BY favorite DESC
LIMIT 20
You might be able to try something like this:
$items = UserItemRel::find()
->asArray()
->select("COUNT(`user_id`) as favourited, `item_id`")
->groupBy("item_id")
->joinWith("item")
->orderBy("favourited DESC")
->indexBy("item_id")
->where("'date_created' >= '".date("Y-m-d", strtotime("-2 days"))."'")
->limit(3)
->all();
In my testing it gives me something like this:
Array
(
[1] => Array
(
[favourited] => 4
[item_id] => 1
[item] => Array
(
[id] => 1
[name] => Donec
[date_created] => 2015-08-26
[date_updated] => 2015-08-26
)
)
[8] => Array
(
[favourited] => 3
[item_id] => 8
[item] => Array
(
[id] => 8
[name] => Tellus
[date_created] => 2015-08-26
[date_updated] => 2015-08-26
)
)
[7] => Array
(
[favourited] => 2
[item_id] => 7
[item] => Array
(
[id] => 7
[name] => Mollis
[date_created] => 2015-08-26
[date_updated] => 2015-08-26
)
)
)
is there a way of getting table name for each column in a postgre result in PHP?
Imagine you have a select with join, for example:
$Q = <<<E2OD
SELECT * FROM user U
LEFT JOIN department D ON U.department_id = D.id
E2OD;
In PHP/FirebirdSQL:
$R = ibase_query($Q);
$D = ibase_fetch_row($R);
$info = ibase_field_info($R, 0);
Returns
Array
(
[0] => id
[name] => id
[1] => id
[alias] => id
[2] => user
[relation] => user
[3] => 8
[length] => 8
[4] => BIGINT
[type] => BIGINT
)
While in PHP/PostgreSQL:
$select = $DB->query($Q);
$meta = $select->getColumnMeta(0);
Returns
Array
(
[pgsql:oid] => 20
[native_type] => int8
[name] => id
[len] => 8
[precision] => -1
[pdo_type] => 2
)
As you see, there's no information about the table the column is from. There's a missing key [relation] => user or similar displaying the table name.
http://php.net/manual/en/pdostatement.getcolumnmeta.php
Can PHP get this information with it's PG or PDO libraries? Does PostgreSQL provide this information to client libraries? What needs to be done to make this happen?
Thanks for any hint,
Michal
Check pg_field_table().