Where to put WHERE in mysql query - mysql

I cannot find where I can put my WHERE clause in my query. It seems like I tried every possible position but nothing is working.
SELECT res
FROM (
SELECT `date`,SUM(DISTRIBUTED_AMOUNT / EXCHANGE_RATE) AS res
FROM royalties
GROUP BY `date`
ORDER BY `date` DESC LIMIT 12
) a
ORDER BY `date` ASC
WHERE `BUNDLE_ARTIST` = '" . $artist_name . "'

I'd have thought you need to put it after the FROM clause in the subquery:
SELECT res
FROM (
SELECT `date`,SUM(DISTRIBUTED_AMOUNT / EXCHANGE_RATE) AS res
FROM royalties
WHERE `BUNDLE_ARTIST` = '" . $artist_name . "'
GROUP BY `date`
ORDER BY `date` DESC LIMIT 12
) a
ORDER BY `date` ASC
You can see this order documented in the MySQL manual.

It seems that you are using an inner query in your clause. You made some mistakes. Try this:
SELECT res
FROM
(
SELECT `date`,SUM(DISTRIBUTED_AMOUNT / EXCHANGE_RATE) AS res
FROM royalties
WHERE `BUNDLE_ARTIST` = '" . $artist_name . "'
GROUP BY `date`
ORDER BY `date` DESC LIMIT 12
) inner query
ORDER BY `date` ASC

Usually, I find including your WHERE clause before the ORDER and GROUP clauses is best:
SELECT res
FROM (
SELECT `date`,SUM(DISTRIBUTED_AMOUNT / EXCHANGE_RATE) AS res
FROM royalties
GROUP BY `date`
ORDER BY `date` DESC LIMIT 12
)
WHERE `BUNDLE_ARTIST` = '" . $artist_name . "'
ORDER BY `date` ASC

Related

LIMIT CLAUSE With union

I have this kind of query. I am using limit, but this query gives me 20 results. Can anybody tell me why
SELECT
*,
`tablename`.`bookmark_id` as `bookmark_id`,
`tablename`.`bookmark_date` as `bookmark_date`
FROM ( (" + sql1 + ")
UNION ALL (" + sql2 + ")
UNION ALL (" + sql3 + ") ) AS tablename
WHERE `bookmark_id`
NOT IN
(SELECT `table1`.`bookmark_id`
FROM (
(SELECT `user_bookmarks`.`bookmark_id`
FROM `user_bookmarks`
WHERE `user_bookmarks`.`bookmark_id` = `bookmark_id`
AND `user_id` = 26)
UNION
(SELECT `bookmark_id`
FROM `user_deleted_bookmarks`
WHERE `user_id` = ?)
) AS `table1`)
GROUP BY bookmark_id
ORDER BY `bookmark_date`
DESC limit 17, 20
Thanks
From the SELECT docs
With one argument, the value specifies the number of rows to return from the beginning of the result set:
SELECT * FROM tbl LIMIT 5; # Retrieve first 5 rows
With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):
SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15
I think you want LIMIT 16, 4
When you use limit, second argument is number of results to return.
See : http://dev.mysql.com/doc/refman/5.0/en/select.html
In your case you want :
SELECT .... LIMIT 16,4
You will get 4 rows : 17, 18, 19 and 20.
SELECT *,`tablename`.`bookmark_id` as `bookmark_id`,`tablename`.`bookmark_date` as `bookmark_date` FROM ( (" + sql1 + ") union all (" + sql2 + ") union all (" + sql3 + ") ) AS tablename WHERE `bookmark_id` NOT IN (SELECT `table1`.`bookmark_id` FROM ((SELECT `user_bookmarks`.`bookmark_id` FROM `user_bookmarks` WHERE `user_bookmarks`.`bookmark_id` = `bookmark_id` AND `user_id` = 26) UNION (SELECT `bookmark_id` FROM `user_deleted_bookmarks` WHERE `user_id` = ?)) AS `table1`) GROUP BY bookmark_id ORDER BY `bookmark_date`
DESC limit 16, 4;
for getting result 17,18,19,20
it's count start from 17th position and give next 4 values

Invalid use of group function - MySQL

This error occurs while I run the select query, please advise.
Error No : 1111
Error : Invalid use of group function
Query:
SELECT cm.contactid, cm.firstname, cm.surname, cm.mobile, COUNT( * ) total
FROM sales_master as sm, contact_master as cm
WHERE sm.contactid = cm.contactid
AND cm.mobile != '' AND orderdate>='2012-12-18' AND orderdate<='2013-03-18'
GROUP BY sm.contactid
HAVING COUNT(*) >= 1
ORDER BY COUNT(*) DESC, cm.firstname ASC
Change your query like this. Use join instead of cartisian. If type of cm.orderdate is DAte than remove DATE() from the below query. And use alias total in GROUP BY and ORDER BY
instead of Count(*) .
SELECT
cm.contactid,
cm.firstname,
cm.surname,
cm.mobile,
COUNT(cm.contactid) total
FROM sales_master as sm
LEFT JOIN contact_master as cm
ON sm.contactid = cm.contactid
WHERE
AND cm.mobile != ''
AND DATE(cm.orderdate) >= '2012-12-18'
AND DATE(cm.orderdate) <= '2013-03-18'
GROUP BY cm.contactid
HAVING total >= 1
ORDER BY total DESC, cm.firstname ASC
There will be two reason:
1) Version compatibility Problem
2) Your query syntax is not ok,I am sending you the solution of second option.
For Version compatibility Problem you must go to the link mentioned by some one on
comment.
You have to use subquery concept for that.
Modify your query something like that:
SELECT sm.contactid ,cm.contactid as contactid , cm.firstname as firstname, cm.surname as surname , cm.mobile as mobile , COUNT( * ) total
FROM (
SELECT sm.contactid,contactid , firstname,surname ,mobile ,total
FROM sales_master as sm, contact_master as cm
WHERE sm.contactid = cm.contactid
AND cm.mobile != '' AND orderdate>='2012-12-18' AND orderdate<='2013-03-18'
GROUP BY sm.contactid
) q
GROUP BY sm.contactid HAVING COUNT(*) >= 1
ORDER BY COUNT(*) DESC, cm.firstname ASC
I am not sure that i made exact query or not but concept is some thing like that means
"Subquery"...

Get last X rows using LIMIT and ORDER BY col ASC

This query is to retrieve some messages, it retuns all of them:
$q = "
SELECT *
FROM pms
WHERE
(
(id_to = $id and id_from = ".sesion().")
OR
(id_from = $id and id_to = ".sesion().")
)
AND (id > $from)
ORDER by fecha ASC";
The thing is i would like to get the last 50 elements, but I think its ony posible using DESC ordering..
how can i do it?
Do i need to count first how many rows so then can I use LIMIT $many-$ipp,$many ? or is there a way to invert the result order?
Just make your query a subquery:
SELECT * FROM
(
SELECT *
FROM pms
WHERE
(
(id_to = $id AND id_from = ".sesion().")
OR (id_from = $id and id_to = ".sesion().")
)
AND id > $from
ORDER BY fecha DESC
LIMIT 50
) q1
ORDER BY fecha ASC

Exclude results of the first query on the second query in same table with MySQL

I want to do like this:
SELECT * FROM `langCategories` ORDER BY `name` ASC WHERE ORDER BY `amount` DESC LIMIT 8,0
but this is not posible.
I have 2 sections in my site:
1. Top 8 Populars Categories
(SELECT * FROM `langCategories` ORDER BY `langCategories`.`amount` DESC LIMIT 0,8)
2. The rest of Categories order by name (excluding the top 8)
(???)
I do it with php:
$var = db_multiselect("SELECT * FROM `langCategories` ORDER BY `amount` DESC LIMIT 0,8");
$var2 = db_multiselect("SELECT * FROM `langCategories` ORDER BY `name` ASC");
$i=-1;
while ($row = mysqli_fetch_array($var)) // Save the top8 categories
{
++$i;
$top8[$i] = $row["name"];
}
$i=0;
while ($row2 = mysqli_fetch_array($var2))
{
if (!(in_array($row2["name"], $top8))) // compare the rest of categories excluding top 8
{
...
}
}
But i want to do this with a MySQL Query, how can do it?
Subquery!
SELECT * FROM (
SELECT * FROM `langCategories`
ORDER BY `langCategories`.`amount` DESC
LIMIT 8,2000000000
) AS baseview
ORDER BY name ASC
Gives you the NOT top 8 categories in alphabetical order
this should work for MySQL (i hope):
SELECT *
FROM (
SELECT lc.*, #rownum:=#rownum+1 AS rownum
FROM `langCategories` lc, (SELECT #rownum:=0) r
ORDER BY `amount` DESC
)
ORDER BY CASE WHEN rownum <= 8 THEN rownum ELSE 999 END, name

Order of "id" changed in subquery?

I have this query
SELECT bul.id
FROM bul
WHERE id IN (SELECT hotid AS parentid
FROM likehot
WHERE hotid IN (SELECT id
FROM bul
WHERE DATE >= '1315976410')
GROUP BY hotpid
ORDER BY COUNT( hotid ) DESC )
when I runt this inner query
SELECT id
FROM bul
WHERE DATE >= '1315976410')
GROUP BY hotpid
ORDER BY COUNT( hotid ) DESC
I get
parentid
3655
3656
3622
3644
and when I run whole query I get
parentid
3656
3655
3622
3644
I really don't understand why the order of the ids change?
SOLUTION :-
<?php
$query_hotpress_like = "SELECT hotid AS parentid FROM likehot WHERE hotid IN (SELECT id FROM bul WHERE DATE >= '" . (time() - (24 * 60 * 60)) . "') GROUP BY hotid ORDER BY COUNT( hotid ) DESC";
$exe_hotpress_like = execute_query($query_hotpress_like, true, "select");
$temp_like1 = array();
foreach ($exe_hotpress_like as $kk => $exe_like) {
$temp_like1[] = "'" . $exe_like['parentid'] . "'";
}
$temp_like = str_replace(",''", "", implode(',', $temp_like1));
$query_hotpress = "SELECT bul.id,photo_album_id,eventcmmnt_id,link_url,youtubeLink,link_image,id, mem_id, subj, body, bul.date,parentid, from_id, visible_to,image_link,post_via FROM bul WHERE id IN ($temp_like) ORDER BY FIELD(id,$temp_like ) LIMIT 5";
?>
execute_query() is the inbuilt function to get the result of query.
That happens because for IN operator order doesn't matter.
If you need to sort outer query - sort outer query.
Since you didn't specify an order for the "whole" query, the database is at liberty to return rows in any order it wants. The specific order you get is a result of how looking up rows is done when using the IN operator.
On your other query you are specifying an order yourself, so the database has to honor it.