How to merge column value? - mysql

How to merge column value in MySQL query? I'm using WordPress for a while now, and I would like to sort data from the price, but each post have different type price (monthly & yearly). The price is stored in wp_postmeta. Here is what I've tried so far.
$mam_global_fields = "
, price.meta_value AS villa_price,
CASE currency.meta_value
WHEN 'IDR' THEN price.meta_value * ". $currency_rate['IDR'] ." / 12
WHEN 'USD' THEN price.meta_value * ". $currency_rate['USD'] ." / 12
WHEN 'EUR' THEN price.meta_value * ". $currency_rate['EUR'] ." / 12
WHEN 'AUD' THEN price.meta_value * ". $currency_rate['AUD'] ." / 12
END AS price_in_usd,
CASE currency_monthly.meta_value
WHEN 'IDR' THEN price_monthly.meta_value * ". $currency_rate['IDR'] ."
WHEN 'USD' THEN price_monthly.meta_value * ". $currency_rate['USD'] ."
WHEN 'EUR' THEN price_monthly.meta_value * ". $currency_rate['EUR'] ."
WHEN 'AUD' THEN price_monthly.meta_value * ". $currency_rate['AUD'] ."
END AS price_in_usd_monthly,
price.meta_key AS price_key,
villa_code.meta_value AS v_codes
";
I join the wp_postmeta multiple times because I want to get the correct data for each post.
$mam_global_join = "
INNER JOIN " . $wpdb->postmeta . " AS currency_monthly ON (" . $wpdb->posts . ".ID = currency_monthly.post_id AND (currency_monthly.meta_key = 'monthly_currency'))
INNER JOIN " . $wpdb->postmeta . " AS price_monthly ON (" . $wpdb->posts . ".ID = price_monthly.post_id AND (price_monthly.meta_key = 'monthly_price'))
INNER JOIN " . $wpdb->postmeta . " AS currency ON (" . $wpdb->posts . ".ID = currency.post_id AND (currency.meta_key = 'currency'))
INNER JOIN " . $wpdb->postmeta . " AS price ON (" . $wpdb->posts . ".ID = price.post_id AND (price.meta_key = 'price'))
INNER JOIN " . $wpdb->postmeta . " AS villa_code ON (" . $wpdb->posts . ".ID = villa_code.post_id AND villa_code.meta_key = 'code')
";
For now it's ordering by 2 columns, but I want to only 1 column that's price_in_usd (but it still showing the wrong villas)
$mam_global_orderby = "price_in_usd, price_in_usd_monthly " . $sort[1];
So how to do this the correct way? because I want to make a sorting programs that will sort the price from both price (yearly or monthly), so if the post have yearly price then the price will be divided by 12. Please help.
I already tried using COALESCE() but I'm stuck, and those codes were the latest version.
EDIT:
Actually I had an idea, but don't know how to do it, I want to get the meta_value to a temporary price, so the yearly or monthly price will be in 1 column, I already looked in google but didn't getting the answer.
EDIT:
What I want, I want to merge the value from two different meta_key (monthly_currency & currency) to a single custom column, that I'll use for sorting, all price will be converted to USD before sorted it, so as you can see, there are CASE currency.meta_value in my code. So after knowing the currency, it'll check if the price if for monthly or yearly, if it's for yearly then it'll divided by 12. So I can sort it by the lowest/highest price, even if it's monthly or yearly rent. The problem I got is, I can't get the correct result, because the price type (yearly / monthly) so how to do it?

Related

Mysql Query With Like Operator and order by keyword giving empty records in spring boot api

native Query I Wrote in My Repository
If i remove order by condition in the below query , it is giving some records but i want it in some order so i added order by condition then it not showing records only . but the same mysql query with order by condition is giving some records in mysql workbench.
#Query(value = "SELECT l.id AS id,l.first_name AS firstName,l.last_name AS lastName,"
+ " l.email AS email,l.phone AS phone,l.place AS place,l.course_id AS courseId,"
+ " c.name AS courseName,l.source AS source,l.enquiry_for AS enquiryFor,"
+ " l.appointment_date AS appointmentDate,l.description AS description,"
+ " l.discount AS discount,l.status AS status,l.assignee_id AS assigneeId,"
+ " ase.first_name AS assigneeFirstName,ase.last_name AS assigneeLastName,"
+ " l.assignor_id AS assignorId,asr.first_name AS assignorFirstName,"
+ " asr.last_name AS assignorLastName,l.active AS active,l.created_date AS createdDate,"
+ " l.updated_date AS updatedDate,(SELECT comments FROM reviews where created_date IN"
+ " (SELECT MAX(created_date) from reviews where lead_id=l.id)) AS latestComment FROM "
+ " leads l JOIN users AS ase ON l.assignee_id = ase.id JOIN users AS asr ON "
+ " l.assignor_id = asr.id JOIN courses AS c ON l.course_id =c.id WHERE l.status!='Draft'"
+ " AND (l.first_name LIKE '%:keyword%' OR l.last_name LIKE '%:keyword%' OR l.phone LIKE"
+ " '%:keyword%') ORDER BY -l.appointment_date DESC,l.created_date ASC", nativeQuery=true)
List<Leads> searchLeadsForAdmin(#Param("keyword") String searchKeyword);
i don't know Where am i going wrong , attached image below mysql query result came in workbench.
I found the answer to my question. It was a concatenation issue. In the second last line of my query after 'l.phone LIKE' I added the value in the next line.
+ " AND l.first_name LIKE %:keyword% OR l.last_name LIKE %:keyword% OR "
+ " l.phone LIKE %:keyword% ORDER BY -l.appointment_date DESC,"
+ " l.created_date ASC", nativeQuery = true)
The above query works.

Using variables on select query table name

i need to use dynamic table names on model select query like this:
$this->db->select("$this->table_car.id as carId, $this->table_car.price as carPrice, $this->table_car.name as carName, $this->table_car.used as carUsed, $this->table_car.visible as carVisible, $this->table_cat.name as catName, $this->table_brand.name as carBrand, $this->table_model.name as carModel");
But variable is not working. This is what I get:
SELECT .`id` AS `carId`, .`price` AS `carPrice`, .`name` AS `carName`, .`used` AS `carUsed`, .`visible` AS `carVisible`, .`name` AS `catName`, .`name` AS `carBrand`, .`name` AS `carModel`
LEFT JOIN ON .`car_id` = .`id`
LEFT JOIN ON .`id` = .`cat_id`
LEFT JOIN ON .`id` = .`brand_model_id`
LEFT JOIN ON .`id` = .`model_id`
LEFT JOIN ON .`id` = .`brand_id`
WHERE .`used`= 0 LIMIT 3
Is there a workaround for this?
Thanks in advance
Whilst double quotes do allow the use of variables inside them without the need to close and concatenate, it doesn't always work for the likes or object and arrays, like you are showing. A better solution would be:
$this->db->select($this->table_car . ".id as carId, "
. $this->table_car . ".price as carPrice, "
. $this->table_car . ".name as carName, "
. $this->table_car . ".used as carUsed, "
. $this->table_car . ".visible as carVisible, "
. $this->table_cat . ".name as catName, "
. $this->table_brand . ".name as carBrand, "
. $this->table_model . ".name as carModel");
Another option would be to put your object variables in braces {} such as :
$this->db->select("{$this->table_car}.id as carId,
{$this->table_car}.price as carPrice,
{$this->table_car}.name as carName,
{$this->table_car}.used as carUsed,
{$this->table_car}.visible as carVisible,
{$this->table_cat}.name as catName,
{$this->table_brand}.name as carBrand,
{$this->table_model}.name as carModel");

Query for choose all orders from all restaurants for the current day

How can I write a mysql query that will choose all the orders of all restaurants for the current day?
Some restaurants may close after 24:00.
So I have three tables:
restaurants with some fields [id, ]
orders with some fields [id, resid, orderdate, ]
hours with some fields [id, resid, day, open, close] the day is a number from 0-6, the open and close are time between 00:00:00 and 23:59:59
Thank you
This is what about i need
SELECT b.*
FROM restaurants a, orders b, hours c
WHERE a.id=b.resid
AND a.id=c.resid
---- here i need the code that will choose the orders for the current working day of the restaurant, but the current working day may include some orders from the previous calendar day if the restaurant close after 24:00
Is this what you want?
select o.*
from orders o
where o.orderdate = curdate();
If not, can you modify your question to better explain what you want?
Because you did not give much information, so I make 2 assumption here
Assumption 1: You run this query at 1AM and want to get all order your 1AM yesterday till now
Assumption 2: No restaurant open 24h day
hours.day = WEEKDAY(SUBDATE(CURDATE(), 1)
If hours.close < hours.open mean restaurant open from YESTERDAY + open_time to TODAY + close_time, otherwise it is open and close on YESTERDAY
STR_TO_DATE(CONCAT(DATE_FORMAT(SUBDATE(CURDATE(), CASE WHEN c.close < c.open THEN 1 ELSE 0 END), '%Y%m%d'), c.close), '%Y%m%d%T')
So your query is something like
SELECT b.*
FROM restaurants a, orders b
WHERE a.id=b.resid
AND a.id in (
select c.resid
from hours c
where c.day = WEEKDAY(SUBDATE(CURDATE(), 1)
and STR_TO_DATE(CONCAT(DATE_FORMAT(SUBDATE(CURDATE(), 1), '%Y%m%d'), c.open), '%Y%m%d%T') > SUBDATE(CURDATE(), 1)
and STR_TO_DATE(CONCAT(DATE_FORMAT(SUBDATE(CURDATE(), CASE WHEN c.close < c.open THEN 1 ELSE 0 END), '%Y%m%d'), c.close), '%Y%m%d%T') <= CURDATE()
)
I'm not sure about orders.orderdate, so you should update your filter on orders table to get correct data you want.
Hope this help
The solution is
" SELECT b.*".
" FROM orders b, rests a, times c ".
" WHERE a.id=b.resid ".
" AND a.id=c.resid ".
" AND (".
"( c.day=dayofweek(subdate(current_date, 1))-1 " .
" AND c.close < c.open " .
" AND c.close> TIME(NOW())" .
" AND b.orderdate>= CONCAT(subdate(current_date, 1),' ',c.open) )" .
" OR " .
"( c.day=dayofweek(current_date)-1 " .
" AND c.close >= c.open " .
" AND c.close> TIME(NOW())" .
" AND b.orderdate>= CONCAT(current_date,' ',c.open) )" .
" OR " .
"( c.day=dayofweek(current_date)-1 " .
" AND c.close < c.open " .
" AND CONCAT(ADDDATE(CURRENT_DATE, 1),' ',c.close)> TIME(NOW())" .
" AND b.orderdate>= CONCAT(current_date,' ',c.open) )" .
")";

How to return largest value of the selected row?

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

Is there any mysql/Oracle function to give incremental no. to one column on the basis of another columns of similar values?

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.