I manage to get the lowest, highest and average price of the item but couldn't get the latest price. Below is the select query i am using by joining the item and item_price tables. How can I fix the problem?
$sql = 'SELECT *, MIN(ip_price) AS lowest_price, MAX(ip_price) AS highest_price,
AVG(ip_price) AS average_price, MAX(ip_price_date) AS latest_date,
(SELECT ip_price FROM cnf_item_price WHERE ip_price_date = "latest_date") AS latest_price
FROM cnf_item
INNER JOIN cnf_item_price ON cnf_item_price.ip_item_id = cnf_item.it_id
WHERE 1 AND cnf_item_price.ip_supp_id=?
GROUP BY cnf_item.it_id
ORDER BY cnf_item.it_name ASC';
$stmt = $DB->prepare($sql);
$stmt->bindValue(1,$supplier_id);
$stmt->execute();
can you try following query:
$sql = 'SELECT *, MIN(ip_price) AS lowest_price, MAX(ip_price) AS highest_price,
AVG(ip_price) AS average_price, MAX(ip_price_date) AS latest_date,
(SELECT ip_price FROM cnf_item_price order by ip_price_date desc limit 1) AS latest_price
FROM cnf_item
INNER JOIN cnf_item_price ON cnf_item_price.ip_item_id = cnf_item.it_id
WHERE 1 AND cnf_item_price.ip_supp_id=?
GROUP BY cnf_item.it_id
ORDER BY cnf_item.it_name ASC';
$stmt = $DB->prepare($sql);
$stmt->bindValue(1,$supplier_id);
$stmt->execute();
Thanks #ahmet kamaran. It's working for my case here. I also replace * with those columns needed as suggested by others. So, after some testing from the above suggestions, here is my codes which retrieve those data i needed.
$sql = 'SELECT it_id, it_code, it_name, it_desc,
ip_id, ip_item_id, ip_supp_id, ip_price, ip_price_date, ip_ref_no, ip_remarks,
MIN(ip_price) AS lowest_price, MAX(ip_price) AS highest_price,
AVG(ip_price) AS average_price, MAX(ip_price_date) AS latest_date,
(SELECT ip_price FROM cnf_item_price ORDER BY ip_price_date DESC LIMIT 1) AS latest_price
FROM cnf_item
INNER JOIN cnf_item_price ON cnf_item_price.ip_item_id = cnf_item.it_id
WHERE 1 AND cnf_item_price.ip_supp_id=?
GROUP BY cnf_item.it_id
ORDER BY cnf_item.it_name ASC';
$stmt = $DB->prepare($sql);
$stmt->bindValue(1,$supplier_id);
$stmt->execute();
http://sqlfiddle.com/#!9/ca6234/2
Thanks.
SELECT it_id, it_code, it_name, it_desc,
ip_id, ip_item_id, ip_supp_id, ip_price, ip_price_date, ip_ref_no, ip_remarks,
MIN(ip_price) AS lowest_price, MAX(ip_price) AS highest_price,
AVG(ip_price) AS average_price, MAX(ip_price_date) AS latest_date,
(SELECT ip_price FROM cnf_item_price WHERE cnf_item_price.ip_item_id = cnf_item.it_id
ORDER BY ip_price_date DESC LIMIT 1) AS latest_price
FROM cnf_item
INNER JOIN cnf_item_price ON cnf_item_price.ip_item_id = cnf_item.it_id
WHERE 1
GROUP BY cnf_item.it_id
ORDER BY cnf_item.it_name ASC;
Related
Im working with GTFS dataset that I have imported into MySql, Im accessing it with PHP.
Im trying to find the trips for a specific route for a given time and date.
My Sql query looks like this
'SELECT t.route_id AS route_id, t.service_id AS service_id, t.trip_headsign AS trip_headsign,
t.trip_id AS trip_id,
( SELECT departure_time
FROM stop_times
WHERE trip_id = t.trip_id
ORDER BY departure_time ASC limit 1) AS initial_departure_time,
( SELECT arrival_time
FROM stop_times
WHERE trip_id = t.trip_id
ORDER BY arrival_time DESC limit 1) AS final_arrival_time
FROM trips AS t INNER JOIN calendar_dates AS c
WHERE t.service_id = c.service_id
AND c.date ='.$calendar_date.'
AND initial_departure_time <='.$time.'
AND'.$time. '<=final_arrival_time
AND t.route_id ='.$route.'
ORDER BY trip_id ASC';
$route, $calendar_date and $time are all passed in.
The query is returning Column not found:
1054 Unknown column 'initial_departure_time' in 'where clause'. Im thinking that initial_departure_time cant be evaluated.
Im completely lost as too how to resolve this. Any clues, thanks in advance
You can't use aliases in your WHERE clause.
Either incorporate the sub-queries into the WHERE clause:
'SELECT t.route_id AS route_id,
t.service_id AS service_id,
t.trip_headsign AS trip_headsign,
t.trip_id AS trip_id,
(SELECT departure_time
FROM stop_times
WHERE trip_id = t.trip_id
ORDER BY departure_time ASC limit 1) AS initial_departure_time,
(SELECT arrival_time
FROM stop_times
WHERE trip_id = t.trip_id
ORDER BY arrival_time DESC limit 1) AS final_arrival_time
FROM trips AS t INNER JOIN calendar_dates AS c
WHERE t.service_id = c.service_id
AND c.date ='.$calendar_date.'
AND (SELECT departure_time
FROM stop_times
WHERE trip_id = t.trip_id
ORDER BY departure_time ASC limit 1) <='.$time.'
AND'.$time. '<= (SELECT arrival_time
FROM stop_times
WHERE trip_id = t.trip_id
ORDER BY arrival_time DESC limit 1)
AND t.route_id ='.$route.'
ORDER BY trip_id ASC';
Or wrap the query and then use the aliases in that:
'SELECT * FROM (
SELECT t.route_id AS route_id,
t.service_id AS service_id,
t.trip_headsign AS trip_headsign,
t.trip_id AS trip_id,
(SELECT departure_time
FROM stop_times
WHERE trip_id = t.trip_id
ORDER BY departure_time ASC limit 1) AS initial_departure_time,
(SELECT arrival_time
FROM stop_times
WHERE trip_id = t.trip_id
ORDER BY arrival_time DESC limit 1) AS final_arrival_time
FROM trips AS t INNER JOIN calendar_dates AS c
WHERE t.service_id = c.service_id
AND c.date ='.$calendar_date.'
AND t.route_id ='.$route.'
ORDER BY trip_id ASC) a
WHERE a.initial_departure_time <='.$time.'
AND'.$time. '<= a.final_arrival_time';
This might speed it up (you may need to swap the MIN and MAX around):
'SELECT t.route_id AS route_id,
t.service_id AS service_id,
t.trip_headsign AS trip_headsign,
t.trip_id AS trip_id,
MIN(s.departure_time) AS initial_departure_time,
MAX(s.arrival_time) AS final_arrival_time
FROM trips AS t
INNER JOIN calendar_dates AS c ON t.service_id = c.service_id
LEFT JOIN stop_times s ON s.trip_id = t.trip_id
WHERE c.date ='.$calendar_date.'
AND t.route_id ='.$route.'
GROUP BY t.route_id, t.service_id, t.trip_headsign, t.trip_id,
HAVING '.$time.' BETWEEN MAX(s.arrival_time) AND MIN(s.departure_time)
ORDER BY trip_id ASC';
Already, when I was using mysql_query, I used FOUND_ROWS() function like this:
$query = 'SELECT SQL_CALC_FOUND_ROWS * FROM Users';
mysql_query($query);
$query = 'SELECT FOUND_ROWS()';
mysql_query($query);
Now I use PDO and here is my query:
$sth = $this->dbh->prepare("SELECT SQL_CALC_FOUND_ROWS *,
u.id user_id,
u.avatar,
u.date_time,
CONCAT(u.user_fname, ' ', u.user_lname) name,
sum($this->table_alias.vote_value) vote_value,
sum($this->table_alias.score) score,
$category_in_the_select AS tc $tag_in_the_select AS tt
FROM users u
JOIN reputations $this->table_alias ON u.id = $this->table_alias.owner_id $query_join
WHERE $time_limitation $query_where
GROUP BY user_id, u.avatar, u.date_time, name, tc, tt
ORDER BY score DESC, vote_value DESC
LIMIT :j, $this->per_page");
$this->parameters[":j"] = $j;
$sth->execute($this->parameters);
$users = $sth->fetchAll(PDO::FETCH_ASSOC);
As you can see, I've used SQL_CALC_FOUND_ROWS in the SELECT statement and I want to know how can I use FOUND_ROWS()?
All you need to do is run a ->query('SELECT FOUND_ROWS()') after your original execute.
$sth = $this->dbh->prepare("SELECT SQL_CALC_FOUND_ROWS *,
u.id user_id,
u.avatar,
u.date_time,
CONCAT(u.user_fname, ' ', u.user_lname) name,
sum($this->table_alias.vote_value) vote_value,
sum($this->table_alias.score) score,
$category_in_the_select AS tc $tag_in_the_select AS tt
FROM users u
JOIN reputations $this->table_alias ON u.id = $this->table_alias.owner_id $query_join
WHERE $time_limitation $query_where
GROUP BY user_id, u.avatar, u.date_time, name, tc, tt
ORDER BY score DESC, vote_value DESC
LIMIT :j, $this->per_page");
$this->parameters[":j"] = $j;
$sth->execute($this->parameters);
$users = $sth->fetchAll(PDO::FETCH_ASSOC);
$count = $this->dbh->query('SELECT FOUND_ROWS()')->fetchColumn();
I'm selecting data from 2 tables.
$sql = "SELECT tb1.id, tb2.name FROM tblA tbl1 LEFT JOIN tblB tbl2 ON tb1.id = tbl2.studentID ORDER BY tbl1.id DESC LIMIT 20";
$statement = $con_db->prepare($sql);
My question is now can I SELECT custom fields from tb1 and all fields in tb2? e.g.
$sql = "SELECT tb1.id, tb1.subject, tb2.(*) FROM ....";
You can write the code like below
$sql = "SELECT tb1.id, tb1.subject, tb2.* FROM tblA tbl1 LEFT JOIN tblB tbl2 ON tb1.id = tbl2.studentID ORDER BY tbl1.id DESC LIMIT 20";
How do I set the field most_popular to 0 if its count is null with a select statement inside a select statement
i've tried IFNULL(SELECT COUNT(*) ...), 0) as most_popular but it won't work and I tried
COALESCE(SELECT COUNT(*) ...., 0) as most_popular
$stmt = $db->prepare("SELECT *,
i.medium_image, i.width, i.height,
(SELECT COUNT(*) FROM order_details od WHERE od.product_id = p.product_id) as most_popular
FROM products p
INNER JOIN product_images i on i.product_id = p.product_id
WHERE p.department_id=:department_id AND p.is_active=1
$orderby
LIMIT :limit OFFSET :offset");
Try this,
SELECT *,
i.medium_image,
i.width,
i.height,
COALESCE(s.totalCount, 0) most_popular
FROM products p
INNER JOIN product_images i
ON i.product_id = p.product_id
LEFT JOIN
(
SELECT product_id, Count(*) totalCount
FROM order_details
GROUP BY product_id
) s ON s.product_id = p.product_id
WHERE p.department_id = :department_id
AND p.is_active = 1
$orderby
LIMIT :limit OFFSET :offset
or how about this, (your current query)
COALESCE((SELECT COUNT(*)
FROM order_details od
WHERE od.product_id = p.product_id), 0) as most_popular
I have a normal mysql select and I would like to rewrite it to a Zend Framework mysql select. Here is my select:
$sql = "
SELECT
IF(mu.recieverUserId = '{$userId}', u.senderUserId,
mu.recieverUserId) friend1,
u.mesaj, u.senderUserId, mu.recieverUserId,
u.created
FROM
(SELECT *
FROM mesaje
ORDER BY `created` desc) AS u
LEFT JOIN `mesaje_utilizatori` AS `mu` ON u.id=mu.mesajId
WHERE (mu.recieverUserId = '{$userId}' OR u.senderUserId='{$userId}')
GROUP BY friend1 ASC
ORDER BY `u`.`created` DESC, u.id DESC
";
Here is the documentation: Zend_Db_Statement
Zend Query
$sql = $db->query(
'SELECT
IF(mu.recieverUserId = ?, u.senderUserId,
mu.recieverUserId) friend1,
u.mesaj, u.senderUserId, mu.recieverUserId,
u.created
FROM
(SELECT *
FROM mesaje
ORDER BY `created` desc) AS u
LEFT JOIN `mesaje_utilizatori` AS `mu` ON u.id=mu.mesajId
WHERE (mu.recieverUserId = ? OR u.senderUserId = ? )
GROUP BY friend1 ASC
ORDER BY `u`.`created` DESC, u.id DESC',
array($userId, $userId,$userId)
);
Zend Result
while ($row = $sql->fetch()) {
Zend_Debug::dump($row);
}