I have a table like this now what i want to do is count the records for each ID where STATUS is COMPLETED
.
Something like SELECT COUNT(*) FROM TABLE WHERE ID= foreach(ID)
AND STATUS=1
select id, count(id) as count from table where status='COMPLETED' group by id;
Basically you need to use group by clause in MySQL.
You can do it using Active Record as this:
I assuming you have you table model named like Job, then you can get a needed value as this:
$number = Job::find()->where(['STATUS' => 'Completed'])->count();
or it is always better to store constant properties in the model like this:
class Job extends ActiveRecord {
const STATUS_COMPLETED = 'Completed';
then your ActiveQuery will look like this:
$number = Job::find()->where(['STATUS' => Job::STATUS_COMPLETED])->count();
Also here is the full description: Querying Data
$any_var = Your_Table::find()->where(['status' => 'Cimpleted'])->select('id')->orderBy('id')->groupBy('id')->count ();
Related
I use Sphinx with Yii2 and need to query with filter by jSON field.
$query = new \yii\sphinx\Query();
$query->from('announcements');
$query->addSelect("*");
$query->addSelect(new Expression("IN(filters['color'], 'blue', 'red', 'green') AS f_color"));
$query->where("is_active = 1");
$query->andWhere("f_color = 1");
$announces = $query->all();
There is jSON field filters in my Sphinx index. For example:
[filters] => {"brand":"Toyota","model":"Prius","color":"red","price":"12000"... etc]
It works OK. But now I need to make a pagination... and there is a problem when I try to count records before $query->all()
$count = $query->count(); // Return error "no such filter attribute 'f_color'"
Generated query was:
SELECT COUNT(*) FROM announcements WHERE ( is_active = 1 ) AND ( f_color = 1 )
count() by default replaces the select part with * and this is where your alias is defined hence the error.
There are different ways to achieve it like:
use ActiveDataProvider like described here,
use META information like described here
Since you want to make a pagination I would go with the first example.
There are two Mysql tables:
1.reservations(id,screening_id,reserved). the reserved is a boolean its value "1".
table seat_reserveds(id,screening_id,reservation_id,seat_id).
I want the following:
1.get the reservation id
select id from reservation where screening_id = id and reserved = 1
In laravel looks like:
$reservation_id = DB::table('reservations')->select('id')-
>where('screening_id',$id)->where('reserved','1')->get();
Then I want to count how many seats are reserved
Select count(id) from seat_resrveds where where screening_id = id and reservtain_id = id.
In laravel looks like:
$reservedtickets = DB::table('seat_reseverds')-
>where('screening_id',$id)->where('reservation_id',$reservation_id)->count('id');
I think the problam is that I get "id":number from $reservation_id so cant use it at the $reservedtitckets query because I only need a number.
How can I write these querys.
Use ->value('id') to get a single value from a query:
$reservation_id = DB::table('reservations')
->where('screening_id',$id)
->where('reserved','1')
->value('id');
Update the query to the following.
$reservation = DB::table('reservations')
->where('screening_id',$id)
->where('reserved', 1)
->first();
Then the $reservation_id should be as below.
$reservation_id = $reservation->id;
You can pass this parameter to your next query for $reservedtickets.
$users = User::where('id', 'parent_id')->get();
The id and the parent_id are in the same table. I want to get all of the data from the users table where the id and parent_id are equal. How can I do that in Laravel?
The issue you are facing is that you want to know how to check if the user has no referrals. You can do it like this:
Add referrer Relation in your user model.
public function referrer()
{
return $this->hasOne(self::class, 'parent_id');
}
You can then query it like this:
User::doesntHave('referrer')->get();
You should try this:
$users = User::whereColumn('id', 'parent_id')->get();
I have come across a scenario where I need to "cast" the output of a function as the column name I want to select:
(SELECT
LOWER(DATE_FORMAT(NOW(), '%b'))
FROM lang_months
WHERE langRef = lang_statements.langRef
) AS month
Just returns the current month which is expected, but I want this to select the column called "may" in this case.
How would I do this?
Thanks, your answer gave me an idea. I just put the current date into a variable and used that in the query like so:
$thisMonth = strtolower(date('M')) ;
(SELECT
$thisMonth
FROM lang_months
WHERE langRef = lang_statements.langRef
) AS month
This is not possible. The name of an entity must be known when the query reaches MySQL.
The easiest option would probably be to determine the column name in whatever language you're using then to just use that. For example, in PHP:
$col = 'someAlias';
$query = "SELECT blah as `{$col}` FROM tbl";
I don't think this is possible.
You could create a view that offers this view on your data so you can they query it more expressively, but you're still going to have to write those 12 subqueries and aliases by hand.
This should work:
$month = LOWER(DATE_FORMAT(NOW(), '%b')); // Results in 'may'
$result = mysql_query('SELECT * FROM $month'); // Returns all records in table 'may'
I have two tables: Users and Groups
In my table "Users", there is a column called "ID" for all the user ids.
In my table "Groups" there is a column called "Participants", fields in this column are filled with all the user ids like this "PID_134,PID_489,PID_4784," - And there is a column "ID" that identifies a specific group.
Now what i want to do, i want to create a menu that shows all the users that are not yet in this particular group.
So i need to get all the user ids, that are not yet in the Participants column of a group with a particular ID.
It would be cool if there was a single mysql query for that - But any PHP + MySQL solutions are okay, too.
How does that work? Any guesses?
UPDATE:
i know, that's not code, but is there a way I could do something like this that would return me a list of all the users?
SELECT *
FROM users, groups
WHERE groups.participants NOT LIKE '%PID_'users.id'%' AND groups.id = 1;
Something like this. You just get rid of "PID_" part of ID.
SELECT * FROM [users] WHERE [id] NOT IN
(SELECT replace(id,'PID_','') FROM groups WHERE group_name='group1')
Group1 would be your variable - group id/name of menu that you've opened.
You can select from multiple tables as shown below:
SELECT * from users, groups WHERE users.id != groups.participants AND groups.id = 1;
This will list all users who are not in group id 1; A more elegant solution can be found by using joins, but this is simple and will do the trick.
I believe something like that should help:
SELECT * FROM users WHERE users.id NOT IN (SELECT groups.participants FROM groups)
But this works only if your DB is normalized. So for your case I see only PHP + MySQL solution. Not very elegant, but it does the job.
<?php
$participants_array = mysql_query("SELECT participants FROM groups");
$ids = array();
while ($participant = mysql_fetch_assoc($participants_array))
{
$id = explode(',', $participant['participant']);
foreach ($id as $instance)
{
if (!in_array($instance, $ids)) $ids[] = $instance;
}
}
$participants = implode(',', $ids);
$result = mysql_query("SELECT * FROM users WHERE id NOT IN ( $participants )");
But I highly recommend normalizing the database.