2 requests in only one using mysql - mysql

I have two requests
UPDATE :
I need to do something like that :
SELECT poste_nom, ups_type_contrat,
(SELECT `entpro_date`
FROM ENT_PRO
WHERE entpro_user_id = 2
ORDER BY `entpro_id` DESC
LIMIT 1) ,
serv_nom,
serv_id_resp,
user_credit_cpf,
user_indice_salarial,
FLOOR( DATEDIFF( CURDATE( ) , user_dateentree ) /365 ) AS dateEntree
FROM USER
INNER JOIN USER_POSTE_SERVICE
ON USER.user_id= USER_POSTE_SERVICE.ups_poste_id
INNER JOIN POSTE
ON USER_POSTE_SERVICE. ups_poste_id = POSTE.poste_id
INNER JOIN SERVICE
ON USER_POSTE_SERVICE.ups_id_serv = SERVICE.serv_id
WHERE user_id = 2
ORDER BY user_nom ASC
Is it possible to gather two requests in only one ?

From what I understood you want to simple merge the result of your sub-query to your main SELECT, if so you could try it this way:
SELECT poste_nom,
ups_type_contrat,
ENT_PRO_RESULT.entpro_date,
serv_nom,
serv_id_resp,
user_credit_cpf,
user_indice_salarial,
FLOOR( DATEDIFF( CURDATE( ) , user_dateentree ) /365 ) AS dateEntree
FROM USER
LEFT JOIN (SELECT entpro_date,
entpro_user_id
FROM ENT_PRO
ORDER BY entpro_id DESC
LIMIT 1) ENT_PRO_RESULT
ON USER.user_id = ENT_PRO_RESULT.entpro_user_id
INNER JOIN USER_POSTE_SERVICE
ON USER.user_id = USER_POSTE_SERVICE.ups_poste_id
INNER JOIN POSTE
ON USER_POSTE_SERVICE.ups_poste_id = POSTE.poste_id
INNER JOIN SERVICE
ON USER_POSTE_SERVICE.ups_id_serv = SERVICE.serv_id
WHERE user_id = 2
ORDER BY user_nom ASC
I've joined it on:
ON USER.user_id = ENT_PRO_RESULT.entpro_user_id
So you only need to specify the:
WHERE user_id = 2
And the sub-query will use the current row user id for the LEFT JOIN.

Related

I have a table like below I want the latest entry to be displayed

The query which I am using now is below:
select ur.uid
, ua.user_activity_min_budget
, ua.user_activity_max_budget
, ua.user_activity_bedroom
, ptm.property_type_description
, cm.city_name
, lm.locality_name
, ua.user_activity_datetime
from user_registration ur
join ksl_user_activity ua
on ua.registered_user_uid = ur.uid
and ua.user_activity_uid = ( select max(ua0.user_activity_uid) from ksl_user_activity ua0)
join ksl_locality_master lm
on lm.locality_uid = ua.user_activity_area
join ksl_city_master cm
on cm.city_uid = lm.city_uid
join ksl_property_type_master ptm
on ptm. property_type_uid = ua.user_activity_property_type
where date(ua.user_activity_datet±me) >= '20l7-07-24'
and (lm.city_uid = 1 or lm.city_uid=2)
order
by ur.uid
The raw output s as this image shows:
The data is what I get now but I want the latest entry for uid 3,15,33
The reason why I have done the below is and ua.user_activity_uid=(select max(ua0.user_activity_uid) from user_activity ua0).
ksl_user_activity table has a primary key user_activity_id which has the maximum value for the latest entry but I am not getting any data when I include this in my query.
I also tried and ua.user_activity_uid=(select ua0.user_activity_uid from user_activity ua0 order by ua0.user_activity_uid desc limit 1)
This is also not working.
use max() function and sub-query
select t1.uid from user_activity t1
inner join
(select uid,max(user_activity_datetime) as user_activity_datetime from user_activity group by uid
) as t2 on
t1.user_activity_datetime=t2.user_activity_datetime
and t1.uid=t2.uid

How to update multiple columns from different table of MariaDB

I am using MariaDB. I am trying to update two columns from SELECT different table.
UPDATE User U
SET
U.UserPoint = (
SELECT ((SELECT COUNT(*)
FROM CARD_COMM R
WHERE R.Card_ID = C.Card_ID) * 3
+
(SELECT COUNT(*)
FROM SECTION_CARD_LIKE L
WHERE L.Card_ID = C.Card_ID) * 1) as userPoint
FROM CARD C WHERE C.userid = U.userid ORDER BY userPoint DESC limit 1 )
this works
UPDATE User U
SET
(U.UserPoint, U.Card) = (
SELECT ((SELECT COUNT(*)
FROM CARD_COMM R
WHERE R.Card_ID = C.Card_ID) * 3
+
(SELECT COUNT(*)
FROM SECTION_CARD_LIKE L
WHERE L.Card_ID = C.Card_ID) * 1) as userPoint,
C.Card_ID as card
FROM CARD C WHERE C.userid = U.userid ORDER BY userPoint DESC limit 1 )
but this dose not....
How do I do this??
please help me...
Use a multi-table update, something like
UPDATE User
JOIN ( SELECT userid, up_value, card_value ... ) AS x
ON x.userid = User.userid
SET User.UserPoint = x.up_value,
User.Card = x.card_value;
(With suitable expressions/subqueries/etc for up_value & card_value)
You seem to be updating all rows in User??

Optimize Query with JOINS and Subqueries

I want to speed up one of my slower queries.
The problem is that I can't access the outer colum value within a subquery.
What I have:
SELECT r.id AS room_id, r.room_name, coalesce(d.score,0) AS total_messages, d.latest
FROM cf_rooms_time_frames tf
INNER JOIN cf_rooms r on r.id = tf.room_id
INNER JOIN(
SELECT cf.room_id, count(*) as score, max(cf.id) as latest
FROM cf_rooms_messages cf
WHERE EXISTS(
SELECT NULL FROM cf_rooms_time_frames tf
WHERE tf.start <= cf.id AND ( tf.end IS NULL OR tf.end >= cf.id )
AND tf.room_id = cf.room_id AND tf.uid = 8
)
GROUP BY cf.room_id
ORDER BY latest
DESC ) d on d.room_id = r.id
WHERE tf.uid = 8
ORDER BY coalesce(latest, score) DESC LIMIT 0, 20
What I want:
SELECT r.id AS room_id, r.room_name, coalesce(d.score,0) AS total_messages, d.latest
FROM cf_rooms_time_frames tf
INNER JOIN cf_rooms r on r.id = tf.room_id
INNER JOIN(
SELECT cf.room_id, count(*) as score, max(cf.id) as latest
FROM cf_rooms_messages cf
/* line added here */
WHERE cf.room_id = tf.room_id
/* */
AND EXISTS(
SELECT NULL FROM cf_rooms_time_frames tf
WHERE tf.start <= cf.id AND ( tf.end IS NULL OR tf.end >= cf.id )
AND tf.room_id = cf.room_id AND tf.uid = 8
)
GROUP BY cf.room_id
ORDER BY latest
DESC ) d on d.room_id = r.id
WHERE tf.uid = 8
ORDER BY coalesce(latest, score) DESC LIMIT 0, 20
I think the markup explains what the query does.
It searches for "chatrooms" for a given user and orders them by the last message, gets the number of total message which ids are in a given range ( timeframes ), and the last message id.
I don't know why, but the first query returns all rows within the chatmessage table ( cf ) if I can trust EXPLAIN. It delivers the correct results but is kind of slow on a huge table.
I tested the second one with a "hardcoded" room_id and this one was very fast and doesn't "touched" the whole table.

Join between sub-queries in SQLAlchemy

In relation to the answer I accepted for this post, SQL Group By and Limit issue, I need to figure out how to create that query using SQLAlchemy. For reference, the query I need to run is:
SELECT t.id, t.creation_time, c.id, c.creation_time
FROM (SELECT id, creation_time
FROM thread
ORDER BY creation_time DESC
LIMIT 5
) t
LEFT OUTER JOIN comment c ON c.thread_id = t.id
WHERE 3 >= (SELECT COUNT(1)
FROM comment c2
WHERE c.thread_id = c2.thread_id
AND c.creation_time <= c2.creation_time
)
I have the first half of the query, but I am struggling with the syntax for the WHERE clause and how to combine it with the JOIN. Any one have any suggestions?
Thanks!
EDIT: First attempt seems to mess up around the .filter() call:
c = aliased(Comment)
c2 = aliased(Comment)
subq = db.session.query(Thread.id).filter_by(topic_id=122098).order_by(Thread.creation_time.desc()).limit(2).offset(2).subquery('t')
subq2 = db.session.query(func.count(1).label("count")).filter(c.id==c2.id).subquery('z')
q = db.session.query(subq.c.id, c.id).outerjoin(c, c.thread_id==subq.c.id).filter(3 >= subq2.c.count)
this generates the following SQL:
SELECT t.id AS t_id, comment_1.id AS comment_1_id
FROM (SELECT count(1) AS count
FROM comment AS comment_1, comment AS comment_2
WHERE comment_1.id = comment_2.id) AS z, (SELECT thread.id AS id
FROM thread
WHERE thread.topic_id = :topic_id ORDER BY thread.creation_time DESC
LIMIT 2 OFFSET 2) AS t LEFT OUTER JOIN comment AS comment_1 ON comment_1.thread_id = t.id
WHERE z.count <= 3
Notice the sub-query ordering is incorrect, and subq2 somehow is selecting from comment twice. Manually fixing that gives the right results, I am just unsure of how to get SQLAlchemy to get it right.
Try this:
c = db.aliased(Comment, name='c')
c2 = db.aliased(Comment, name='c2')
sq = (db.session
.query(Thread.id, Thread.creation_time)
.order_by(Thread.creation_time.desc())
.limit(5)
).subquery(name='t')
sq2 = (
db.session.query(db.func.count(1))
.select_from(c2)
.filter(c.thread_id == c2.thread_id)
.filter(c.creation_time <= c2.creation_time)
.correlate(c)
.as_scalar()
)
q = (db.session
.query(
sq.c.id, sq.c.creation_time,
c.id, c.creation_time,
)
.outerjoin(c, c.thread_id == sq.c.id)
.filter(3 >= sq2)
)

Optimizing django has_perm database query

Model method has perm looks for all the permission from Group and Permission. which is a heavy query.How can i optimized query time or any other solution to check user permission.
Example:
SELECT "auth_permission"."id", "auth_permission"."name", "auth_permission"."content_type_id", "auth_permission"."codename" FROM "auth_permission" INNER JOIN "auth_group_permissions" ON ( "auth_permission"."id" = "auth_group_permissions"."permission_id" ) INNER JOIN "auth_group" ON ( "auth_group_permissions"."group_id" = "auth_group"."id" ) INNER JOIN "auth_user_groups" ON ( "auth_group"."id" = "auth_user_groups"."group_id" ) INNER JOIN "django_content_type" ON ( "auth_permission"."content_type_id" = "django_content_type"."id" ) WHERE "auth_user_groups"."user_id" = 1235 ORDER BY "django_content_type"."app_label" ASC, "django_content_type"."model" ASC, "auth_permission"."codename" ASC
SELECT "auth_permission"."id", "auth_permission"."name", "auth_permission"."content_type_id", "auth_permission"."codename", "django_content_type"."id", "django_content_type"."name", "django_content_type"."app_label", "django_content_type"."model" FROM "auth_permission" INNER JOIN "auth_user_user_permissions" ON ( "auth_permission"."id" = "auth_user_user_permissions"."permission_id" ) INNER JOIN "django_content_type" ON ( "auth_permission"."content_type_id" = "django_content_type"."id" ) WHERE "auth_user_user_permissions"."user_id" = 1235 ORDER BY "django_content_type"."app_label" ASC, "django_content_type"."model" ASC, "auth_permission"."codename" ASC