I have the following sample query (MySQL):
SELECT * FROM `action`
WHERE `customer_id` IN
(SELECT `id` FROM `customer` WHERE `status`=1)
ORDER BY
action.date ASC
LIMIT 0, 10
I need to be able to ORDER BY the customer.status field. Do I accomplish this with a join?
status is a field on the customer table.
Edited Query:
SELECT * FROM `action`
ORDER BY
action.date ASC
LIMIT 0, 10
IMPORTANT!
I am parsing the return data via PHP. After running the revised query:
SELECT * FROM `action` a INNER JOIN `customer` c ON a.customer_id = c.id ORDER BY a.form_id ASC LIMIT 0, 10
My PHP code breaks...
This post helped me out.
My revised query looks like this:
SELECT
*, a.id AS lead_id, c.id AS customer_id
FROM
`action` a
INNER JOIN
`customer` c ON a.customer_id = c.id
ORDER BY c.status DESC
Thanks everyone!
UPDATE
Because I have some customer records without an action record, an INNER JOIN was not returning all relevant records. I use a JOIN now, and all results come back as expected.
SELECT *
FROM `action` a
INNER JOIN `customer` c on a.`customer_id` = c.`id`
WHERE c.`status` in (1, 4, 7, 8)
ORDER BY a.date, c.status
LIMIT 0, 10
You can do either:
SELECT * FROM `action` a
INNER JOIN `customer` c on c.id = a.customer_id
WHERE c.status = 1
ORDER BY a.date ASC, c.status
LIMIT 0, 10
Or:
SELECT * FROM `action` a
INNER JOIN `customer` c on (c.id = a.customer_id and c.status = 1)
ORDER BY a.date ASC, c.status
LIMIT 0, 10
EDIT:
It's probably worth pointing out there's no sense in ordering by c.status, as it will always be 1. However, I put that in there since it was brought up by others as well as mentioned in the OP. I would think it could be removed from both queries.
Yes, you may accomplish it with a join and may be faster:
SELECT * FROM `action` a join customer c on c.id=a.customer_id
where c.status=1
ORDER BY
a.date ASC
LIMIT 0, 10
Also, consider not using * and instead list the columns that you need. It will improve performance in case you need to select less than all columns and you won't get surprises in the future if the table changes.
SELECT * FROM `action` a
JOIN `customer` c on a.customer_id=c.id
WHERE c.status=1 order by a.date, c.status ASC
LIMIT 0, 10
Related
I have this query that will LEFT JOIN and GROUP BY to get SUM of column.
SELECT
c.id,
SUM(
r.score
) AS score_sum,
SUM(
CASE WHEN r.is_active = '0' THEN r.negative ELSE 0 END
) AS negative_sum
FROM comments AS c
LEFT JOIN rates AS r ON (r.comment_id = c.id)
WHERE r.comment_id = c.id
GROUP BY c.id
DB Fiddle link:
https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=fadba795d8426f91471fa4db83845b6f
The query works, but if the comments records is large (10K for example), I need to implement pagination, how do I modify this query to limit the comments records first before GROUP BY?
In short:
Get the first 5 comments by limit to 5
Left join the table rates
Get the SUM by group by
Example, show the first 4 comments SUM
Thanks
You can use subquery to "select c.id from comments limit N" in the FROM clause.
select c.id,
sum(r.score) as score_sum,
SUM(
CASE WHEN r.is_active = '0' THEN r.negative ELSE 0 END
) AS negative_sum
from ( select c.id from comments c limit 2) c
LEFT JOIN rates AS r ON (r.comment_id = c.id)
GROUP BY c.id;
You may apply order by in the subquery to determine order in which you want to select the comments (Top N).
DB Fiddle link
Try the following:
SELECT
c.id,
SUM(
r.score
) AS score_sum,
SUM(
CASE WHEN r.is_active = '0' THEN r.negative ELSE 0 END
) AS negative_sum
FROM comments AS c
LEFT JOIN rates AS r ON (r.comment_id = c.id)
WHERE r.comment_id = c.id
GROUP BY c.id
ORDER BY c.id ASC
LIMIT 5
The rationale behind the above query is that id is the Primary key (hence indexed) in your comments table. Also, your GROUP BY and ORDER BY is on the same column, that is, id; so MySQL will first utilize the index on id and get first 5 rows (due to LIMIT), and then proceed forward to JOIN with other tables and do aggregation etc.
Give it a Try!! More details here: https://dev.mysql.com/doc/refman/5.7/en/order-by-optimization.html
We can confirm the same using EXPLAIN .. on this query.
I have a query
SELECT s.*
, g.*
from tbl_section1 as s
, tbl_game as g
LEFT
JOIN tbl_game_visit_count AS gvc
ON g.game_id = gvc.game_id
where s.category_id = g.game_id
ORDER
BY g.udate DESC
, gvc.visit_count DESC
which works fine.
But I want to fetch the first record ordered by g.udate, and then the rest of the records ordered by gvc.visit_count.
Is this possible using mysql query?
Thanks in advance.
It could be possible by using UNION(not UNION ALL, since we don't want to duplicate rows ) between two queries with ORDER BY and LIMIT clauses inside parentheses
SELECT q.*
FROM
(
SELECT s.*, g.*
FROM tbl_section1 as s
INNER JOIN tbl_game as g ON s.category_id = g.game_id
LEFT JOIN tbl_game_visit_count AS gvc ON g.game_id = gvc.game_id
ORDER BY g.udate DESC
LIMIT 1
) q
UNION
SELECT s.*, g.*
FROM tbl_section1 as s
INNER JOIN tbl_game as g ON s.category_id = g.game_id
LEFT JOIN tbl_game_visit_count AS gvc ON g.game_id = gvc.game_id
ORDER BY gvc.visit_count DESC;
P.S. Because of your original query I kept DESC options for ORDER BY, you can get rid of them if you want regular ascending ordering.
Is it possible to convert this subquery to join?
SELECT `news`.`newsId`,
(SELECT `comments`.`text`
FROM `comments`
WHERE `comments`.`newsId` = `news`.`newsId`
order by `comments`.`date` desc
limit 1)
FROM `news` , `comments`
where `news`.`newsId` = `comments`.`newsId`
GROUP BY `news`.`newsId`
order by news.date desc;
I assume newsId is unique.
SELECT `news`.`newsId`,
`comments`.`text`
FROM `news`
CROSS APPLY (SELECT `comments`.`text`
FROM `comments`
WHERE `comments`.`newsId` = `news`.`newsId`
order by `comments`.`date` desc
limit 1) cm
order by news.date desc;
I think that what you're trying to do is:
SELECT n.newsId FROM news n
INNER JOIN comments c ON c.newsId = n.newsId
ORDER BY c.date DESC, n.date
LIMIT 1
The GROUP BY is not necessary as you are not using any aggregation function. You can have unique entries with DISTINCT
In mysql query I use order by, but it is not working.
When I do this
SELECT t.id,t.user_id,t.title,c.comment,d.has_answer,IF(c.id IS NULL, t.date_created, d.recent_date) recent_date,MIN(i.id) image_id
FROM threads t
LEFT JOIN comments c ON c.thread_id = t.id
INNER JOIN (
SELECT thread_id, MAX(date_sent) recent_date, MAX(is_answer) has_answer
FROM comments
GROUP BY thread_id
) d ON c.id IS NULL OR (d.thread_id = c.thread_id AND d.recent_date = c.date_sent)
LEFT JOIN thread_images i ON t.id = i.thread_id
WHERE t.user_id = t.user_id
GROUP BY t.id
ORDER BY d.recent_date DESC
LIMIT 0, 10
It doesn't properly order them. But if I do this:
SELECT *
FROM (
SELECT t.id,t.user_id,t.title,c.comment,d.has_answer,IF(c.id IS NULL, t.date_created, d.recent_date) recent_date,MIN(i.id) image_id
FROM threads t
LEFT JOIN comments c ON c.thread_id = t.id
INNER JOIN (
SELECT thread_id, MAX(date_sent) recent_date, MAX(is_answer) has_answer
FROM comments
GROUP BY thread_id
) d ON c.id IS NULL OR (d.thread_id = c.thread_id AND d.recent_date = c.date_sent)
LEFT JOIN thread_images i ON t.id = i.thread_id
WHERE t.user_id = t.user_id
GROUP BY t.id
LIMIT 0, 10) qwerty
ORDER BY recent_date DESC
Then it does work. Why does the top one not work, and is the second way the best way to fix that?
Thanks
Those two statements are ordering by two different things.
The second statement is ordering by the result of an expression in the SELECT list.
But the first statement specifies ordering by a value of recent_date returned by the inline view d; if you remove "d." from in front of recent_date, then the ORDER BY clause would reference the alias assigned to the expression in the SELECT list, as the second statement does.
Because recent_date is an alias for an expression the SELECT list, these two are equivalent:
ORDER BY recent_date
ORDER BY IF(c.id IS NULL, t.date_created, d.recent_date)
^^
but those are significantly different from:
ORDER BY d.recent_date
^^
Note that the non-standard use of the GROUP BY clause may be masking some values of recent_date which are discarded by the query. This usage of the GROUP BY clause is a MySQL extension to the SQL Standard; most other relational databases would throw an error with this statement. It's possible to get MySQL to throw the same type of error by enabling the ONLY_FULL_GROUP_BY SQL mode.
Q Is the second statement the best way to fix that?
A If that statement guarantees that the resultset returned meets your specification, then it's a workable approach. (One downside is the overhead of the inline view query.)
But I strongly suspect that the second statement is really just masking the problem, not really fixing it.
SELECT t.id,t.user_id,t.title,c.comment,d.has_answer,IF(c.id IS NULL, t.date_created, d.recent_date) recent_date,MIN(i.id) image_id
FROM (threads t
LEFT JOIN comments c ON c.thread_id = t.id
INNER JOIN (
SELECT thread_id, MAX(date_sent) recent_date, MAX(is_answer) has_answer
FROM comments
GROUP BY thread_id
) d ON c.id IS NULL OR (d.thread_id = c.thread_id AND d.recent_date = c.date_sent)
LEFT JOIN thread_images i ON t.id = i.thread_id
WHERE t.user_id = t.user_id
GROUP BY t.id
LIMIT 0, 10) x
ORDER BY d.recent_date DESC
Here is my MySQL database:
And my query to get all subcategories:
SELECT `a`.`id`, `a`.`name`, `a`.`url_segment`, `a`.`categories_id`, `b`.`image` AS supplements_image
FROM (`subcategories` AS a)
LEFT JOIN `supplements` AS b ON `b`.`subcategories_id` = `a`.`id`
LEFT JOIN `reviews` AS c ON `c`.`supplements_id` = `b`.`id`
GROUP BY `a`.`id`
ORDER BY `a`.`categories_id` ASC, COUNT(c.id) DESC, `b`.`image` ASC
The problem is with the subcategory image, that should be the image of a random product inside that subcategory, but I'm always getting the image of the first product. Any idea how I can do this?
SELECT `a`.`id`, `a`.`name`, `a`.`url_segment`, `a`.`categories_id`,
(SELECT `image`
FROM `supplements`
WHERE `subcategories_id` = `a`.`id`
ORDER BY RAND() LIMIT 1
) AS supplements_image
FROM (`subcategories` AS a)
LEFT JOIN `reviews` AS c ON `c`.`supplements_id` = `a`.`id`
GROUP BY `a`.`id`
ORDER BY `a`.`categories_id` ASC, COUNT(c.id) DESC
Edited unspecified alias b and now works great: See fiddle!