can this sql query be simplified? - mysql

I have 2 tables. MySql
users : A_ID,name
event : B_ID, A_ID,cat_id,date
Now I want to get all users , who participated more at events on a given period of time, and need to add based on category too. I am doing something like this :
select name from users ,
(select A_id, count(*)
from event
where date<=givendate
group by A_id
order by count(*) desc ) e
where users.A_id=e.a_id
limit 0,5
Is there any easy and prof way to write that script ?
Thanks

Your query looks OK apart from a few minor points:
Your ORDER BY and LIMIT should be in the outer select otherwise the order of the results is indeterminate.
Use the JOIN keyword to join two tables.
Try this:
SELECT u.name
FROM users AS u
JOIN
(
SELECT A_id, COUNT(*) AS cnt
FROM event
WHERE date <= givendate
AND cat_id = 42
GROUP BY A_id
) AS e
USING (A_id)
ORDER BY e.cnt DESC
LIMIT 5

Related

How to only get DISTINCT rows from a JOIN query: MySQL

Two tables. Table one is users. Table two is user events. One user has many events. I just want to get a list of the users with the most recent events. I can obviously set it to select more rows than I need and filter out the duplicates but I really want to just select the exact number of rows I need in the SQL.
This SQL query gives duplicates of a.name where one user has had more than one event recently. I thought that DISTINCT would prevent duplicates. What am I doing wrong? How do I just get one row for each user?
SELECT DISTINCT (a.name), b.date , a.id
FROM `users` a
INNER JOIN events b
ON a.id = b.userid
WHERE now() > b.date
ORDER BY b.date DESC, a.id DESC
LIMIT 30;
Table users...
id name
Table events...
id userid date
I don't need to select the b.date value but this is needed for DISTINCT to work because it is in the ORDER BY part, I believe.
You could GROUP BY the user and only take the maximum date (or the minimum, if you want the oldest of the events).
SELECT a.name,
max(b.date) date,
a.id
FROM users a
INNER JOIN events b
ON a.id = b.userid
WHERE now() > b.date
GROUP BY a.id,
a.name
ORDER BY max(b.date) DESC,
a.id DESC
LIMIT 30;
DISTINCT won't help you, when there are different date values for a user. Those records are distinct because of the different date values, though sharing a user.

Particular MySql Query

Having the following tables
Post(*id, name, description, cat, publish_date)
Category(*id, name)
It is possible in ONE query to get (max) the first N element of each different category?
Assuming that N=3, i'd need the following result:
Result set:
["1", "Name1","Descr","cat1"]
["2", "Name1","Descr","cat1"]
["3", "Name1","Descr","cat1"]
["10","Name1","Descr","cat2"]
["20","Name1","Descr","cat2"]
["22","Name1","Descr","cat2"]
["25","Name1","Descr","cat3"]
["30","Name1","Descr","cat3"]
["19","Name1","Descr","cat3"]
And so on.
I need this, to get the first N article of EACH category, with one query (so without ask for a specific category but for all category in table)
It is possible? If yes what's the right query?
This query will do what you need. If any category has less than 3 post it will still work.
SELECT P.id,P.name,P.description,C.name
FROM Post P
LEFT JOIN Category C
ON P.type = C.id
WHERE FIND_IN_SET(P.id,
(
SELECT GROUP_CONCAT(ids) FROM
(SELECT SUBSTRING_INDEX(GROUP_CONCAT(id),',',3) as ids
FROM Post
GROUP BY type
) AS foo
GROUP BY ''
)
)
Here is a working SQL Fiddle
UPDATE
In response to your comment and updated question:
SELECT P.id,P.name,P.description,P.publish_date,C.name
FROM Post P
LEFT JOIN Category C
ON P.type = C.id
WHERE FIND_IN_SET(P.id,
(
SELECT GROUP_CONCAT(ids) FROM
(SELECT SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY publish_date DESC),',',3) as ids
FROM Post
GROUP BY type
) AS foo
GROUP BY ''
)
)
You can use UNION to join multiple queries into one. This assumes that you know what type you are selecting for each set.
SELECT * FROM
(
SELECT * FROM T1 WHERE type='Type1' ORDER BY id DESC LIMIT 3
) DUMMY1
UNION ALL
SELECT * FROM
(
SELECT * FROM T1 WHERE type='Type2' ORDER BY id DESC LIMIT 3
) DUMMY2
UNION ALL
SELECT * FROM
(
SELECT * FROM T1 WHERE type='Type3' ORDER BY id DESC LIMIT 3
) DUMMY3
The DUMMY table aliases are needed to allow ordering within each subquery.

Subquery - records are not in ordered form

I have three tables:
user: id, name
keyword: id, name
userkeyword: id, user_id, keyword_id
I want to execute query in following way:
Display those users whose keyword/s are matched with the login user's
keywords. In the order of maximum number of keyword matched user
should display first
e.g : If userA having 4 matched keywords, userB having 8, userC having 1, userD having 6 then the result should be in the order of,
userB
userD
userA
userC
For that I have done with this query (assume login user's id is 1):
select *
from user
where id IN (
select user_id
from userkeywords
where keyword_id IN (
select keyword_id
from userkeywords
where user_id=1)
group by user_id
order by count(keyword_id) desc)
AND id != 1
Here the result is getting perfect but the order is not correct. I have merged two queries in following manner"
select *
from user
where id IN (?)
AND id!=1
+
select user_id
from userkeywords
where keyword_id IN (
select keyword_id
from userkeywords
where user_id=1)
group by user_id
order by count(keyword_id) desc
Second query returns user_id in correct order but when I merged both queries, order was changed (wrong).
Hope I have mentioned my query properly with enough detail.
A subquery returns an unordered set, so the order by in a subquery only matters for its limit clause, if there is any. Any database other than MySQL would give an error message for a purely decorative sort order.
There's no way to sort on a column that only exists in the where clause. You'd have to rewrite the query. One option is to replace your in conditions with joins:
select uk2.name
from userkeywords uk1
join userkeywords uk2
on uk1.keyword_id = uk2.keyword_id
and uk1.user_id <> uk2.user_id
join user u2
on u2.id = uk2.user_id
where uk1.user_id = 1
group by
uk2.name
order by
count(*) desc
This should do it.
select uk.user_id, u.name
from userkeywords uk
left join user u on u.id = uk.user_id
where uk.keyword_id IN (
select keyword_id
from userkeywords
where user_id=1)
group by uk.user_id
order by count(uk.keyword_id) desc) AND uk.user_id != 1
Also, JOIN provides better performance.
I would use an inner join to select the correct rows:
SELECT *
FROM user
INNER JOIN (
SELECT * FROM userkeyword
WHERE keyword_id IN (
SELECT keyword_id
FROM userkeyword
WHERE user_id=1
)
) uk
ON user.id = uk.user_id
GROUP BY u.id
ORDER BY count(*) DESC;

mysql query select * from table where image!='' order by date and with different upload user

I want to make some mysql query, query out 5 image order by date, but from 5 different upload user.
mysql datatable Structure: id, user_id, image, text, date
SELECT *
FROM mytable
WHERE image!=''
GROUP BY user_id
ORDER BY date DESC
LIMIT 5
But this GROUP BY always cause get the user_id earlier upload image then make a ORDER BY date DESC, I need the fresh 5 images which uploaded by 5 differents users. Maybe should use some UNION, ask for a help, thanks.
Use INNER JOIN with MAX
SELECT
mytable.*
FROM
mytable
INNER JOIN
(SELECT MAX(id) AS ID, id FROM mytable GROUP BY user_id) AS m
ON m.id = mytable.id
WHERE image != ''
GROUP BY user_id
ORDER BY DATE DESC
LIMIT 5
This will fetch the max(latest) id and integrate it to the outer select
Try this query
SELECT *
FROM temp
WHERE image!=''
GROUP BY user_id
HAVING date=max(date)
LIMIT 5
Not sure about mysql but this works in sybase.

Selecting rows with unique field values in mysql

I have these columns for table comments:
id
content
add_date
uid
school_id
Rows can have the same school_id.
I want to select the latest data according to add_date, but only 1 row per school_id (no duplicate for school_id) with limit of 10.
I've tried many codes already and its not working for me.
Any help would be appreciated.
This is what we call Greatest N per Group. You can achieved this by putting into a subquery so it can be joined against the non-grouped table (comments).
Try this:
SELECT c.*
FROM
(
SELECT school_id, MAX(add_date) maxDate
FROM comments
GROUP BY school_id
) x INNER JOIN comments c
ON x.school_id = c.school_ID AND
x.maxDate = c.add_date
ORDER BY x.maxDate desc
LIMIT 10
select C.ID, C.Content, t1.MaxDate as [add_date], C.uid, t1.school_id
from (selet school_id, max(add_Date) as 'MaxDate'
from comments
group by school_id) T1
inner join comments C on T1.school_id = C.school_id and C.add_Date= T1.MaxDate
LIMIT 10
If you want to choose which 10 rows return, add an order by, or a Where clause
select c1.*
from comments c1
where add_date = (select max(add_date) from comments c2 where c2.school_id =c1.school_id)
order by add_date desc
limit 10
create indexes on comments(add_date) and comments(school_id, add_date)