Yii2 converting a normal query into eloquent - yii2

How to write this in Yii2 using Query Builder?
SELECT * FROM `report_details` order by `report_id` <> 5, reference_no
Thanks.

If you want to show report_id at top and then same reference_no record, you can use direct sql using UNION. If ReportDetails is the model name:
$reportId = 2;
$referenceNo = 5;
$sql = sprintf("
select * from report_details where report_id = %d
union distinct
select * from report_details where reference_no = %d
", $reportId, $referenceNo);
$rows = ReportDetails::findBySql($sql)->all();
Check this sql fiddle: http://sqlfiddle.com/#!9/d7cb6/2

Related

MySQL LIMT is a subquery?

I want to use a select statement to control the limit of another select query, I cant get it to work, what I have below. The Select in the braces returns an INT.
Im newer to MySQL so im not sure what I should use instead to get this to work.
SELECT *
FROM `tbl_prod`
WHERE prod_id = 32
ORDER BY prod_level ASC , prod_date
LIMIT
(SELECT max_count
FROM Prod_subscription
WHERE prod_id = 32)
You can't write subquery in LIMIT, but you can use dynamic SQL to make your expected result.
SET #num = (
SELECT max_count
FROM Prod_subscription
WHERE prod_id = 32);
PREPARE STMT FROM 'SELECT *
FROM `tbl_prod`
WHERE prod_id = 32
ORDER BY prod_level ASC , prod_date
LIMIT ?';
EXECUTE STMT USING #num;

Can this query be optimized somehow?

Is this is a good query in performance or I can somehow optimize this query? I need to select date column from rental_schedules table and count how many available same dates are available (rental_schedule_status = 1):
$reservationTimes = RentalSchedule::distinct()
->select('date',
DB::raw('(SELECT count(date) FROM rental_schedules AS r2
WHERE r2.date = rental_schedules.date and rental_schedule_status = 1) as free_time'))
->where('premises_id', $id)->pluck('free_time', 'date');
Thanks in advance!
You could try to phrase your query using left join to a subquery, e.g.
SELECT
rs1.date,
COALESCE(rs2.cnt, 0) AS free_time
FROM rental_schedules rs1
LEFT JOIN
(
SELECT date, COUNT(*) AS cnt
FROM rental_schedules
WHERE rental_schedule_status = 1
GROUP BY date
) rs2
ON rs1.date = rs2.date
WHERE
rs1.premises_id = ?;
Your updated Laravel code:
$reservationTimes = RentalSchedule:from("RentalSchedule AS rs1")
->select(DB::raw('rs1.date, COALESCE(rs2.cnt, 0) AS free_time'))
->join(DB::raw('(SELECT date, COUNT(*) AS cnt
FROM rental_schedules
WHERE rental_schedules_status = 1
GROUP BY date) rs2'),
function($join) {
$join->on('rs1.date', '=', 'rs2.date');
})
->where('premises_id', $id)
->pluck('free_time', 'date');
You may also try adding an index on (rental_schedules_status, date), to speed up the subquery:
CREATE INDEX idx ON rental_schedules (rental_schedules_status, date)
You can get result without join or subquery :
Try this :
$reservationTimes = RentalSchedule::select('date',\DB::Raw("sum(case when rental_schedule_status = 1 then 1 else 0 end) as free_time"))
->where('premises_id', $id)
->groupBy('date')
->get()
->pluck('free_time', 'date');

How to get all rows with using WHERE using SQL

I am looking for something, which can select all rows in db using WHERE like this:
SELECT * FROM fb_post WHERE fb_page_id = 17 AND YEAR(date) = ALL ORDER BY date
So, In my app, I set date from local variable.
SELECT * FROM fb_post WHERE fb_page_id = 17 AND YEAR(date) = ? ORDER BY date
In some case, I want to select all years, is there any key word for select all? I don't want to write second query like this:
SELECT * FROM fb_post WHERE fb_page_id = 17 ORDER BY date
Thank you for help
If you send parameter null in order to get all, the below code will help you on mysql. For Mssql replace IFNULL with ISNULL and NVL for Oracle.
SELECT * FROM fb_post WHERE fb_page_id = 17 AND YEAR(date) = IFNULL('your param here',YEAR(date))
You can add a boolean that conditions the date check:
SELECT * FROM fb_post
WHERE fb_page_id = 17 AND (NOT checkDate OR YEAR(date) = ALL)
ORDER BY date
If you set checkDate to false, YEAR(date) = ALL will be ignored.

MySQL: Get rows with creation date string newer than given date string

I am trying to create a prepared statement with following code:
$statement = $db->prepare("SELECT * FROM myTable WHERE
STR_CMP(creationDate, $startingDate) = 1 ORDER BY creationDate DESC ");
I have also tried this:
$statement = $db->prepare("SELECT * FROM myTable WHERE
(creationDate > $startingDate) = 1 ORDER BY creationDate DESC ");
But I am getting null $statement. My goal is to get rows which it's creatrion date is newer than given date string. My creationDate column is stored as string.
I have logged my query string and it look like:
SELECT * FROM myTable WHERE (creationDate > 05.02.2015 14:08:31) = 1 ORDER BY creationDate DESC
What am I doing wrong?
1) You have to compare date to date.
SELECT * FROM myTable WHERE
DATE_FORMAT(STR_TO_DATE(creationDate, '%d.%m.%Y %H:%i:%s'),'%d.%m.%Y %H:%i:%s')
> '.$startingDate.' ORDER BY creationDate DESC
Tips
2) Store date in DB as date not string
3) Your date string seems to invalid?
Why not YYYYMMDD.
ORDER BY creationDate DESC may implict unexpected reulsts
I have solved my problem by trying my query string in my phpMyAdmin sql query section of my database. And I have relized when I build my query like this:
$statement = $db->prepare("SELECT * FROM myTable WHERE
(creationDate > $startingDate) = 1 ORDER BY creationDate DESC ");
It becomes:
SELECT * FROM myTable WHERE (creationDate > 05.02.2015 14:08:31) = 1
ORDER BY creationDate DESC
and MySql gives error for 05.02.2015 14:08:31
So I have prepared my statement like this:
$queryString = 'SELECT * FROM arendi_ideas WHERE (creationDate > "'.$startingDate.'") = 1 ORDER BY creationDate DESC';
$this->logger->debug("GetIdeasNewerThan: Query string = $queryString");
$this->statement = $this->db->prepare($queryString);
and it works fine.

How to select all rows where date column are like a '2015-01-21'?

Im' trying to select all the rows with a concrete user and also on a specific date. My query always return "0", and this is no possible.
The column called "date-column" have a DATE format.
$my_date = '2015-01-21';
$q_search = $mysqli->query("SELECT *
FROM table_name
WHERE userID = ".$_SESSION['memberID']." AND
date_column = ".$my_date."");
echo 'number of results: '.$q_search->num_rows.';
Any ideas?
Insert query should be like this
$sql=" SELECT * FROM table_name WHERE userID = '$_SESSION[memberID]' AND date_column = '$my_date'";
You need to add ' in you date, like this
$q_search = $mysqli->query("SELECT * FROM table_name WHERE userID = ".$_SESSION['memberID']." AND date_column = '" . $my_date . "'");
You should quote the parameters:
$q_search = $mysqli->query("SELECT * FROM table_name WHERE userID = '".$_SESSION['memberID']."' AND date_column = '".$my_date."';");
I suggest you to sanitize the parameters with the function mysql_real_escape_string before concatenating them in the query, like that:
$q_search = $mysqli->query("SELECT * FROM table_name WHERE userID = '".mysqli_real_escape_string($_SESSION['memberID'])."' AND date_column = '".mysqli_real_escape_string($my_date)."';");