Yii2 : LeftJoin query with Where clause & orderBy clause - mysql

I have write query to get distinct stateID whose status is active, from tbl_summer table which is primary key of table tbl_states.
I want the listing of distinct state names in alphabetical order.
Actually i got this from following query but alphabetical order is not getting...
So what is the solution...?
Here is my query :
$query = Tbl_summer::find()
->select('tbl_summer.StateID, tbl_states.state_name')
->distinct('tbl_summer.StateID')
->from('tbl_summer')
->leftJoin('tbl_states', ['tbl_states.ID' => 'tbl_summer.StateID'])
->where(['tbl_summer.IsActive' => '1'])
->orderBy(['tbl_states.state_name' => SORT_ASC]);

Does this work?
$query = Tbl_summer::find()
->select('tbl_summer.StateID, tbl_states.state_name')
->from('tbl_summer')
->leftJoin('tbl_states', ['tbl_states.ID' => 'tbl_summer.StateID'])
->where(['tbl_summer.IsActive' => '1'])
->groupBy('tbl_summer.StateID, tbl_states.state_name')
->orderBy(['tbl_states.state_name' => SORT_ASC]);
I think the second field in groupBy is not needed if there is only one name for one id.

Related

Laravel query builder not returning the full row if it does not find a join with another table

Here, my currently working query is
$results = DB::table('amenities as a')
->leftJoin('amenity_values as av','av.amenity_id','=','a.id')
->leftJoin('units_amenities_values as uav','uav.amenity_value_id','=','av.id')
->leftJoin('units as u','uav.unit_id','=','u.id')
->leftJoin('amenity_pricing_reviews as apr','apr.unit_id','=','u.id')
->select('a.id as amenity_id','a.amenity_name','a.category_id', 'av.amenity_value','u.id as unit_id','u.unit_number','apr.dom','apr.building_id')
->where('a.property_id', $data['property_id'])
->whereIn('apr.building_id', $data['building_ids'])
->whereNull('apr.deleted_at')
->whereNull('u.deleted_at')
->whereNull('av.deleted_at')
->whereNull('a.deleted_at')
->orderBy('a.amenity_name','asc')
->get()
->groupBy(['category_id','unit_id']);
Here, I have joined to a table amenity_pricing_reviews. In this relationship whenever it could not find the related rows in the amenity_pricing_reviews table it is discarding the full rows:
However, I want to get these rows with an empty value for those columns from that table. Something like:
amenity_id => value
amenity_name => value
category_id => value
amenity_value => value
unit_id => value
unit_number => value
dom =>
building_id =>
Also, I have done a lot of other things based on the result of this query so I want to make minimal changes to the structure of the end result.
Your whereIn condition can't succeed if the amenity pricing review doesn't exist, so it effectively changes your left joins into inner joins. Perhaps you want that to be just a condition of the join?
->leftJoin('amenity_pricing_reviews as apr', function($join) { $join->on('apr.unit_id','=','u.id')->whereIn('apr.building_id', $data['building_ids']) })
Try join instead of leftJoin. This should help

Alias for table

I have two tables. The first - Product, the second - Category. They contain fields with the same name - 'name'.
In model Product I added following code:
public function getCategory(){
return $this->hasOne(Category::className(), ['id' => 'cat_id']);
}
I need to show in GridView the column from table Category. I added following code for this in the model ProductSearch:
$query->joinWith(['category' => function($query) { $query->from(['cat' => 'category']); }]);
This code adds the alias cat for the table Category.
After that I got an error:
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'name' in where clause is ambiguous
The SQL being executed was: SELECT COUNT(*) FROM `product` LEFT JOIN `category` `cat` ON `product`.`cat_id` = `cat`.`id` WHERE `name` LIKE '%aasdadadsdgdgdg%'
Error Info: Array
(
[0] => 23000
[1] => 1052
[2] => Column 'name' in where clause is ambiguous
)
How can I add the alias for the table Product?
Open your ProductSearch model, navigate to the search($params) method. Below you should see the filtration part:
$query->andFilterWhere(['like', 'name', $this->name])
fix the ambigous part by writing table name product to that line.
$query->andFilterWhere(['like', 'product.name', $this->name])
or..
$query->andFilterWhere(['like', self::tableName() . '.name', $this->name])
This'll giving precise info that name should be queried from product.name table.
The interesting part is that you don't get the error until you join the Category table.
Imho, it's the worst to find this errors as it seems like everything is working, until search functionality is used.

mysql DELETE rows when multiple conditions are met

So, I have following wpdb DELETE function:
$wpdb->delete( $table, array( 'sub_id' => $sub_id ) ????);
I want to delete rows where WHERE two conditions are met
For example, when sub_id = $sub_id AND date = $date, then I want to delete a row where these two conditions are available.
How do I change above function?
Thanks
You can go in this direction:
$wpdb->query("DELETE FROM table_name WHERE 'sub_id'=".$sub_id." AND date=".$date);
If you want to use multiple where conditions, than the second parameter should be a associative array. The conditions will be joined with "AND".
$wpdb->delete($wpdb->prefix . 'table_name', array('sub_id' => $sub_id, 'date' => $date));
Following query will be generated:
DELETE FROM wp_table_name WHERE sub_id = 1 AND date = 2017-07-17 00:00:00
For more info look here: DELETE Rows

Selecting distinct values from key/value pairs in a seperate table

I have 2 database tables
JOBS(JOB_ID, JOB_TIME, JOB_NAME,...), JOB_PARAMETERS(JOB_ID,NAME,VALUE)
where JOB_PARAMETERS is essentially a map containing job parameter key value pairs.
Every job may have a unique parameter key/value pairs.
I am looking to pragmatically build a query that will return distinct job id's that contain key/value combinations. Where the values are actually a list of values, comparison operators.
For example:
JOB_PARAMETERS: NAME = 'OUTPUT_FILENAME', VALUE LIKE "ALEX%", "JAX%"
NAME = 'PRIORITY' , VALUE > 7
The above example would automatically filter out all jobs that don't have the OUTPUT_FILENAME and PRIORITY key. Returning All jobs that meet both conditions.
I also need to be able to support pagination and order by.
I was planning on using Perl with DBIx::Class, But I can do it in pure Perl/SQL as well.
I am open to changing the database schema, but every job can have different key/value pairs, so I cant just make them columns in the jobs table.
Thanks in advance.
When using DBIx::Class you can generate a DBIC schema by using Schema::Loader.
After connecting to the database you get a $schema object you can use to get a ResultSet filtered to return the Result objects you want:
my $rs_job_parameters = $schema->resultset('Job_Parameters')->search({
-or => [
{
'name' => 'OUTPUT_FILENAME',
'value' => [{ like => 'ALEX%'}, { like => 'JAX%' }].
},
{
'name' => 'PRIORITY',
'value' => [{ '>' => 7}].
}
]},
{
columns => [qw( job_id )],
group_by => [qw( job_id )], # alternative you can use distinct => 1 to group_by all selected columns
having => \[ 'COUNT(*) = ?', [ 2 ] ],
}
);
my #job_ids = $rs_job_parameters->get_column('job_id')->all;
One can do it in SQL, by grouping JOB_PARAMETERS by JOB_ID and filtering the groups accordingly. For example, if there is a uniqueness constraint over (JOB_ID, NAME), one can query as follows:
SELECT JOB_ID
FROM JOB_PARAMETERS
WHERE (NAME='OUTPUT_FILENAME' AND (VALUE LIKE 'ALEX%' OR VALUE LIKE 'JAX%'))
OR (NAME='PRIORITY' AND VALUE > 7)
GROUP BY JOB_ID
HAVING COUNT(*) = 2
Absent such a uniqueness constraint, COUNT(*) would have to be replaced e.g. with COUNT(DISTINCT NAME).

Using get_user in wordpress with sorting

I have wp_users table which has a column ordering. I came to know that get_users() returns all the users.
I am using it like get_users('orderby=ordering')
I got help form this link
But unfortunately it is not sorting on ordering column.
Any help?
You should first take a look at the users table from the database.
The command you try is good, but the argument you use for ordering might be wrong. You should order by a column from the users table, for example user name, or user id's..
On the link you mentioned I've found these:
orderby - Sort by 'ID', 'login', 'nicename', 'email', 'url', 'registered', 'display_name', or 'post_count'.
order - ASC (ascending) or DESC (descending).
Some working examples:
Get users by nicename:
$users = get_users('orderby=nicename');
Other examples:
Display users sorted by Post Count, Descending order
$user_query = new WP_User_Query( array ( 'orderby' => 'post_count', 'order' => 'DESC' ) );
Display users sorted by registered, Ascending order
$user_query = new WP_User_Query( array ( 'orderby' => 'registered', 'order' => 'ASC' ) );