I want to build query after in laravel 5
SELECT * FROM tbl WHERE updated_at IN (
SELECT max(updated_at) FROM tbl
WHERE created_at BETWEEN $begin_time AND $end_time
GROUP BY ip_address)
My code:
$sqlStr = self::select('*')
->whereIn('updated_at', function($query){
return $query->select(self::raw('max(updated_at)'))
->whereRaw('created_at >= $begin_time)
->whereRaw('created_at <= $end_time)
->groupBy('ip_address');
})->toSql();
var_dump(($sqlStr));die;
Error information:
ErrorException in Grammar.php line 58:
strtolower() expects parameter 1 to be string, object given
Please help me.
When you wrote self::raw('max(updated_at)') that generates SELECT max(updated_at) FROM tbl which is already inside a select command. Following code will work:
$sqlStr = self::select('*')
->whereIn('updated_at', function($query) {
$query->selectRaw('max(updated_at)')
->from('tbl')
->whereRaw('created_at >= $begin_time')
->whereRaw('created_at <= $end_time')
->groupBy('ip_address');
})->toSql();
Or this should work too:
DB::select(
'SELECT * FROM tbl WHERE updated_at IN (' .
'SELECT max(updated_at) FROM tbl ' .
'WHERE created_at BETWEEN :begin_time AND :end_time ' .
'GROUP BY ip_address '
')',
[
'begin_time' => $begin_time,
'end_time' => $end_time
]
);
Related
I'm using node js to develope my project, i use mysql to store my data.
I have a problem when i select with like query, and it give an error like this:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'test'%' ORDER BY create_time DESC LIMIT 0,10' at line 1
SELECT * FROM user WHERE fullname LIKE N'%'test'%' ORDER BY create_time DESC LIMIT 0,10
I know error here is 'test' in query, but it's a string, i can't remove it, my code here:
data = {};
data.fullname = 'test';
data.start = 0;
data.limit = 10;
let getFullname = function (data, callback) {
return db.query("SELECT * FROM user WHERE fullname LIKE N'%?%' ORDER BY create_time DESC LIMIT ?,? ", [data.fullname,data.start,data.limit], callback);
}
How can i solve my problem, thank you!
You are right, problem is mysql package add single quote ', you can use following manner
return db.query(`SELECT * FROM user WHERE fullname LIKE N'%${data.fullname}%' ORDER BY create_time DESC LIMIT ?, ? `, [data.start,data.limit], callback);
or
data.fullname = '%' + data.fullname + '%';
return db.query("SELECT * FROM user WHERE fullname LIKE N? ORDER BY create_time DESC LIMIT ?,? ", [data.fullname,data.start,data.limit], callback);
CONCAT("%", ? , "%")
:)
this is part of my code :
##########
where += ` AND ( titre LIKE CONCAT("%", ? , "%") OR resume LIKE CONCAT("%", ? , "%") ) ` ;
vals.push(dataRes.rech) ;
vals.push(dataRes.rech) ;
#############
sql = `SELECT ######### WHERE 1=1 ${where}` ;
connection.query( sql , vals , async function(err, services, fields) {
if(err) rej({er : 1 , code : err , sql: sql , vals : vals}) ;
else{ res({er : 0 , data : services }) }
How to use TDateTimePicker with time format (hour:minute:second)?
I tried this code:
Sql.text:= ('select * from namatabel where namafield between '+quotedstr(formatdatetime('yyyy/mm/dd', datetimepicker1.date))+' and '+quotedstr(formatdatetime('yyyy/mm/dd', datetimepicker2.date))+' and field order by field ASC');
Also this code:
Sql.text:= ('select * from tablename where fieldname between '+quotedstr(formatdatetime('yyyy/mm/dd hh:mm:ss', datetimepicker1.date))+' and '+quotedstr(formatdatetime('yyyy/mm/dd hh:mm:ss', datetimepicker2.date))+' and fieldname order by fieldname ASC');
Also this code:
Sql.text:= ('select * from tablename where fieldname between '+quotedstr(formatdatetime('yyyy/mm/dd hh:mm:ss', datetimepicker1.datetime))+' and '+quotedstr(formatdatetime('yyyy/mm/dd hh:mm:ss', datetimepicker2.datetime))+' and fieldname order by fieldname ASC');
but those wont work, help me to correct them.
I'm using SQLYog against a MySQL database.
UPDATE
#Jens Borrisholt i try this code before, but it doesnt work either
SQL.Add('SELECT meteran.kd_meter as no,kamar.nama,meteran.waktu,meteran.meter '+
'FROM meteran,kamar WHERE kamar.idkamar = meteran.idkamar AND meteran.waktu BETWEEN :tgl1 and :tgl2 and waktu group by waktu asc');
ParamByName('tgl1').AsString:=FormatDateTime('yyyy-mm-dd',DateTimePicker1.DateTime);
ParamByName('tgl2').AsString:=FormatDateTime('yyyy-mm-dd',DateTimePicker2.DateTime); end;
DBGrid2.DataSource.DataSet:=MyQuery2;
Your query is wrong
and fieldname is too much
shortened with data
NOT OK
Sql.text:= 'select * from tablename where fieldname between "2006-06-11"'+
'and "2006-06-19" and fieldname order by fieldname ASC';
OK
Sql.text:= 'select * from tablename where fieldname between "2006-06-11" '+
'and "2006-06-19" order by fieldname ASC';
example valid SQL with data
select * from auktionen where auktionende between '2006-06-11' and '2006-06-19' order by auktionende ASC;
All together with your code. without and waktu
BETWEEN :tgl1 and :tgl2 and waktu
MyQuery2.Close;
MyQuery2.SQL.Text := 'SELECT meteran.kd_meter as no,kamar.nama,meteran.waktu,meteran.meter '+
'FROM meteran,kamar WHERE kamar.idkamar = meteran.idkamar'+
' AND meteran.waktu BETWEEN :tgl1 and :tgl2'+
' group by waktu';
MyQuery2.ParamByName('tgl1').AsString:=FormatDateTime('yyyy-mm-dd',DateTimePicker1.Date);
MyQuery2.ParamByName('tgl2').AsString:=FormatDateTime('yyyy-mm-dd',DateTimePicker2.Date);
DBGrid2.DataSource := DataSource1;
MyQuery2.Open;
I mt sure what is your exact requirement.ill try to help you.
I)If you want to compare the date of the datetimepicker against a date of datetime field in table,
SQL.Add(format('select * from tablename where cast ([my_date_time_var] as date) between %s and %s ' ,[Quotedstr(FormatDateTime('MM/DD/YYYY',(datepicker1.Date))),Quotedstr(FormatDateTime('MM/DD/YYYY',(datepicker2.Date)))]))
II)If you want to compare the date time of the datetimepicker against a date time of datetime field in the table,
SQL.Add(format('select * from tablename where my_date_time_var between %s and %s ' ,[Quotedstr(FormatDateTime('MM/DD/YYYY HH:MM:SS',(datepicker1.DateTime))),Quotedstr(FormatDateTime('MM/DD/YYYY HH:MM:SS',(datepicker2.DateTime)))]));
III)If you want to compare the time of the datetimepicker against a time of datetime field in table,
SQL.Add(format('select * from tablename where cast ([my_date_time_var] as time) between %s and %s ' ,[Quotedstr(FormatDateTime('HH:MM:SS',(datepicker1.time))),Quotedstr(FormatDateTime('HH:MM:SS',(datepicker2.Time)))]))
Please let me know if your requirement is not the same
I've not come across this before. Here's the query:
$query="SELECT
CONCAT_WS(' ',
TRIM(SUBSTRING_INDEX(
SUBSTRING(document, 1, INSTR(document, 'Quickstart') - 1 ),
' ',
-8)
),'Quickstart',
TRIM(SUBSTRING_INDEX(
SUBSTRING(document, INSTR(document, 'Quickstart') + LENGTH('Quickstart') ),
' ',
5)
)
)
FROM documents WHERE MATCH(document)
AGAINST('Quickstart' IN BOOLEAN MODE )";
And here's the resulting array:
[0] => Array
(
[CONCAT_WS(' ',
TRIM(SUBSTRING_INDEX(
SUBSTRING(document, 1, INSTR(document, 'Quickstart') - 1 ),
' ',
-8)
),'Quickstart',
TRIM(SUBSTRING_INDEX(
S] =>
Quickstart for set up. 1. Register your
)
The last part it's returning seems to be correct:
Quickstart for set up. 1. Register your
But why is the query itself returned? Here's the php:
if (!$result = mysql_query($query)) send(mysql_error(),"e");
$hitArray=array();
while ($row=mysql_fetch_array($result, MYSQL_ASSOC) ) { $hitArray[]=$row; }
Thanks for taking a look.
It's not returning itself, it's the key in the array, try to assign an alias to the CONCAT_WS part:
SELECT
CONCAT_WS( ... ) as concatenated
FROM documents WHERE MATCH(document)
AGAINST('Quickstart' IN BOOLEAN MODE )
I am using codeigniter's active record, but i've realized I probably need a regular SQL query for what I'm trying to accomplish. Could someone please look at this code and give me the correct format. What am I doing wrong here?
I think it's obvious what I'm trying to accomplish just by reading the code, but if you need more than just the syntax i've used (obviously in error), I'm happy to provide an explanation of code.
$today = date('Y-m-d H:i:s');
$where = "type == pk_card AND (end_date > $today OR qty >= 1)";
$this->db->select('id, title, pk_card_set, pk_card_number');
$this->db->from('auctions');
$this->db->where($where);
$this->db->like("CONCAT(title, ' ', pk_card_number, ' ', pk_card_set)", $keyword);
$query = $this->db->get();
There are number of mistakes in your code the way you are trying to query through active record
type == pk_card -> mysql if you want to compare any value against your column you need single = sign not double == correct one is type = 'pk_card'
type == pk_card ->Again if you want to compare any string value against column you need to wrap it with standard single quotes ' like type = 'pk_card'
end_date > $today if you want to compare date then again you need warp date string in single quotes like end_date > '$today'
And now you can write your active record query as below
$today = date('Y-m-d H:i:s');
$keyword='Test';
$where = "(end_date > '$today' OR qty >= 1)";
$this->db->select("id, title, pk_card_set, pk_card_number ");
$this->db->from('auctions');
$this->db->where($where,null,FALSE);
$this->db->where('type','pk_card');
$this->db->like("CONCAT(title, ' ', pk_card_number, ' ', pk_card_set)", $keyword);
$query = $this->db->get();
this will generate a query similar to
SELECT
`id`,
`title`,
`pk_card_set`,
`pk_card_number`
FROM
(`auctions`)
WHERE (
end_date > '2014-08-10 12:47:06'
OR qty >= 1
)
AND `type` = 'pk_card'
AND CONCAT(
title,
' ',
pk_card_number,
' ',
pk_card_set
) LIKE '%Test%'
Active Record
I want to simplify the following using dynamic SQL like one could do in Transact SQL.
I want to do something like:
SET #s = replace(field_name, '_complete','')
and use #s instead of replace(field_name, '_complete','')
Please adive if possible and if so how.
My current code:
select distinct
if(instr(replace(field_name, '_complete',''),'_') <= 5
,left(replace(field_name, '_complete','')
,instr(replace(field_name, '_complete',''),'_') - 1
)
,replace(field_name, '_complete','')
) AS form_id ,replace(
if(instr(replace(field_name, '_complete',''),'_') <= 5,
mid(replace(field_name, '_complete',''),
instr(replace(field_name, '_complete',''),'_') + 1,
length(replace(field_name, '_complete','')) - instr(replace(field_name, '_complete',''),'_')
)
,replace(field_name, '_complete','')
),
'_',
' ') as form_name ,field_name from redcap_extract2use where field_name like '%_complete' order by 1;
The above would then be replaced with:
select distinct
if(instr(#s,'_') <= 5 ,left(#s,instr(#s,'_') - 1),#s ) AS form_id
,replace( if(instr(#s,'_') <= 5,
mid(#s,instr(#s,'_') + 1,length(#s) - instr(#s,'_')),#s), '_', ' ') as form_name
,field_name
from redcap_extract2use
where field_name like '%_complete'
order by 1;
and I would have an execute... to run the query
If I'm understanding your question correctly then you would want to use the PREPARE and the EXECUTE statements.
For example:
SET #s = replace(field_name, '_complete','');
PREPARE mystatement FROM
SELECT DISTINCT ...... ;
EXECUTE mystatement;