I'm trying to construct a wp query that creates a string for each record:
$ttr_a = $wpdb->get_results("
SELECT CONCAT(
'"TR4":"',
t2.TaxAccount,
'", "',
CASE WHEN t1.TypeID = '1' THEN '"TR6":"Text A", '
WHEN t1.TypeID = '2' THEN '"TR6":"Text B", '
ELSE
CONCAT('"TR6":"', t1.NewID, '", ')
END
)
AS TID
FROM " . $wpdb->prefix . "table1 t1
LEFT JOIN " . $wpdb->prefix . "table2 t2
ON t1.NewID = t2.TaxCode
WHERE ID = " . $ID);
This query works fine in phpMyAdmin but the double quotes break the wpdb query. Is there some way to escape these? I've tried replacing with apostrophe and escaping the double qoutes with a double quote but nothing seems to work. If there are syntax errors here, please ignore them as I've just extracted what is needed, my sql query does work in mysql.
You should use a prepared statement here if at all possible. If that be not possible, then to escape literal double quotes inside a string defined with double quotes, try escaping the literal ones with backslashes:
$ttr_a = $wpdb->get_results("
SELECT CONCAT(
'\"TR4\":\"',
t2.TaxAccount,
'\", \"',
CASE WHEN t1.TypeID = '1' THEN '\"TR6\":\"Text A\", '
WHEN t1.TypeID = '2' THEN '\"TR6\":\"Text B\", '
ELSE
CONCAT('\"TR6\":\"', t1.NewID, '\", ')
END
)
AS TID
FROM " . $wpdb->prefix . "table1 t1
LEFT JOIN " . $wpdb->prefix . "table2 t2
ON t1.NewID = t2.TaxCode
WHERE ID = " . $ID);
I can't find a clear answer to this and my tests where inconclusive:
If I have a column in a table in a join that must be equal to (or in another relation with) a constant, is faster to put the condition in ON? Or at the end in WHERE?
Example:
SELECT * FROM `" . BLABLA . "` as `s`
JOIN `" . BLABLABLA . "` AS `sDet` ON (`sDet`.`a` > '" . $R['a'] . "'
AND '" . $R['b'] . "' BETWEEN `sDet`.`c` AND `sDet`.`d`
AND `s`.`id` = `sDet`.`idDet`
)
WHERE `s`.`f` = 'whatever'
Or
SELECT * FROM `" . BLABLA . "` as `s`
JOIN `" . BLABLABLA . "` AS `sDet` ON (`s`.`id` = `sDet`.`idDet`)
WHERE `s`.`f` = 'whatever'
AND '" . $R['b'] . "' BETWEEN `sDet`.`c` AND `sDet`.`d`
AND `s`.`id` = `sDet`.`idDet`
I was thinking first version should be faster but I'm not sure. Any thoughts?
I'm not quite sure whats quicker but do keep in mind that conditions are not always interchangeable between the where and on clause.
Inner join
In case of an INNER JOIN they are interchangable
Outer join
In case of an OUTER JOIN they are not necessarily interchangeable. It depends on which side of the join the conditions depends
The following query is working perfectly :
SELECT *
FROM MsUser
WHERE absensi_tanggal = DATE_FORMAT( STR_TO_DATE( "' .$query_array['datepicker'] . '", \'%m/%d/%Y\' ) , \'%Y-%m-%d\' )
However, this query is not working. I should miss something there :
SELECT *
FROM MsUser
WHERE absensi_tanggal BETWEEN DATE_FORMAT( STR_TO_DATE( "' .$query_array['datepicker1'] . '", \'%m/%d/%Y\' ) , \'%Y-%m-%d\' )
AND DATE_FORMAT( STR_TO_DATE( "' .$query_array['datepicker2'] . '", \'%m/%d/%Y\' ) , \'%Y-%m-%d\' )
The query above always return 0 result.
Any help is appreciated, Thanks :D
Since STR_TO_DATE returns a proper DATE type value that can be used with BETWEEN, have you tried simply:
SELECT *
FROM MsUser
WHERE absensi_tanggal
BETWEEN
STR_TO_DATE( "' .$query_array['datepicker1'] . '", \'%m/%d/%Y\' )
AND
STR_TO_DATE( "' .$query_array['datepicker2'] . '", \'%m/%d/%Y\' )
My guess would be that MySQL is choking on converting front a string to a date and then back to a string and then back again to a date to make the BETWEEN work.
Also, try this to make it a bit tidier:
"
SELECT *
FROM MsUser
WHERE absensi_tanggal
BETWEEN
STR_TO_DATE('{$query_array['datepicker1']}','%m/%d/%Y')
AND
STR_TO_DATE('{$query_array['datepicker2']}','%m/%d/%Y');
"
And just in case you aren't confirming that the value of datepicker1 is earlier than datepicker2, you can run the query like this to be sure (though I advise only for testing):
SELECT *
FROM MsUser
WHERE
(
absensi_tanggal
BETWEEN
STR_TO_DATE('{$query_array['datepicker1']}','%m/%d/%Y')
AND
STR_TO_DATE('{$query_array['datepicker2']}','%m/%d/%Y')
) OR (
absensi_tanggal
BETWEEN
STR_TO_DATE('{$query_array['datepicker2']}','%m/%d/%Y')
AND
STR_TO_DATE('{$query_array['datepicker1']}','%m/%d/%Y')
);
"
I'm trying to select latest date in row (not in column)
It must be 'articles_date_added' or 'articles_last_modified' in table like that
Id | ... | ... | articles_date_added | articles_last_modified | ...
My real query looks like:
select
a.articles_id, a.authors_id, a.articles_date_added,
a.articles_last_modified,
IF(a.articles_last_modified >= a.articles_date_added,
a.articles_last_modified,
a.articles_date_added) as latestdate,
ad.articles_viewed,
ad.articles_name, ad.articles_head_desc_tag,
COUNT(vh.articles_id) as total_votes,
SUM(v.vote_value)/COUNT(v.vote_value) AS vote_avg,
au.authors_name, td.topics_name, a2t.topics_id
from
" . TABLE_ARTICLES . " a
left join " . TABLE_AUTHORS . " au using(authors_id)
left join VOTE_HISTORY vh using (articles_id)
left join VOTE v using (vote_id),
" . TABLE_ARTICLES_DESCRIPTION . " ad,
" . TABLE_ARTICLES_TO_TOPICS . " a2t
left join " . TABLE_TOPICS_DESCRIPTION . " td using(topics_id)
where
(a.articles_date_available IS NULL or
to_days(a.articles_date_available) <= to_days(now())) and
a.articles_status = '1' and a.articles_id = a2t.articles_id and
ad.articles_id = a2t.articles_id and
ad.language_id = '" . (int)$languages_id . "'
and td.language_id = '" . (int)$languages_id . "'
and a2t.topics_id = '" . (int)$current_topic_id . "' and
au.authors_id = '" . (int)$_GET['filter_id'] . "'
GROUP BY a.articles_id
ORDER BY latestdate desc
As you can see to select it I use
IF(a.articles_last_modified >= a.articles_date_added,
a.articles_last_modified, a.articles_date_added) as latestdate
but it returms 1054 - Unknown column 'latestdate' in 'order clause
Why?
I'm on MySql 5.0.
Since adding is a modification, it'd be a good idea if your a.articles_last_modified would contain the same date as a.articles_date_added upon inserting a row.
UPDATE `articles`
SET `articles_last_modified` = `articles_date_added`
WHERE `articles_last_modified` = '0000-00-00 00:00:00'
ALTER TABLE `articles`
CHANGE COLUMN `articles_last_modified` `articles_last_modified`
TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
This way you won't need this condition in where clausule
I am interested to know that Is there any mysql/Oracle function to give incremental no. to one column on the basis of another columns of similar values?
Like in my below code, I have order_primary column which contains order no. so based on that we can identify how many products belongs to particular order. Also count is for storing those values like 1,2,3 etc.
But I am facing problem that count value is just going incrementaing...
My code-:
$query_product = "SELECT name, id,qty_ordered,price,row_total,base_subtotal,
base_shipping_amount,base_grand_total,order_primary,message
FROM sales_order WHERE `prod_Flag`=0 ";
$result_query_product = mysql_query($query_product);
$count = 0;
while($row = mysql_fetch_array($result_query_product))
{
$count++;
$name = ($row["name"]);
$message1 = ($row["message"]);
$result_str_product .= "('". mysql_real_escape_string($name) . "',". "'" . $row["sku"] . "'," . "'" . $row["qty_ordered"] . "',". "'" . $row["price"] . "'," . "'" . $row["row_total"] . "'," . "'" . $row["base_subtotal"]. "'," . "'" . $row["base_shipping_amount"] . "'," . "'" . $row["base_grand_total"] ."',". $row["order_primary"].",". $count.",". "'".mysql_real_escape_string($message1)."'".", NOW()),";
}
$query_prod_insert = "INSERT into sales_product(name, sku, qty_ordered, price, row_total, base_subtotal, base_shipping_amount,base_grand_total,prod_foreign,count,message,product_creation_date) VALUES ".$result_str_product;
$final_query = substr_replace($query_prod_insert,";",-1);
$result_query_product_outbound = mysql_query($final_query);
So My o/p is-:
('shirt','st','2.0000','75','150','150','20','170',29,1,NOW()),
('tie' ,'te','2.0000','50','100','100','10','110',29,2,NOW()),
('tie' ,'te','2.0000','50','100','100','10','110',29,3,NOW()),
('socks','sk','5.0000','20','100','100','05','105',30,4,NOW());
('jackt','jt','3.0000','40','120','120','15','135',30,5,NOW());
But I want o/p like this-:
('shirt','st','2.0000','75','150','150','20','170',29,**1**,NOW()),
('tie' ,'te','2.0000','50','100','100','10','110',29,**2**,NOW()),
('tie' ,'te','2.0000','50','100','100','10','110',29,**3**,NOW()),
('socks','sk','5.0000','20','100','100','05','105',30,**1**,NOW());
('jackt','jt','3.0000','40','120','120','15','135',30,**2**,NOW());
So Is there any mysql/Oracle function to give incremental no. to one column on the basis of another columns of similar values i.e. in my case, for same order no. value say 29, count values should be 1,2,3 & for same order no. 30, count value should be 1,2...
So is there any function or how to do the same.
For Oracle this is pretty easy:
SELECT order_no,
row_number() over (partition by order_no order by order_primary) as rn
FROM sales_product
Note: I'm guessing the column names as they are somewhere hidden in the PHP(?) code. Please adjust them according to your table structure. For future posts you should also include the corresponding CREATE TABLE statement in your question.