MySQL LEFT JOIN only one row, ordered by column without subquery - mysql

Is there a possibility to do LEFT JOIN with only one row from other table ordered by column (date) without using sub query. My query is below. It works but it's super slow.
SELECT * FROM clients c
LEFT JOIN loan l ON c.id = l.id_client AND l.id = (
SELECT id FROM loan ll
WHERE ll.id_client = c.id
ORDER BY `create_date` DESC
LIMIT 1)
GROUP BY k.id DESC
ORDER BY c.register_date DESC
LIMIT n , m; (n,m is from pagination)
Is there a way to speed it up?

Im interpreting your question as "Get me all loan details for the most recent loan for each client"
This should work... note the assumption though.
SELECT *
FROM
clients c
LEFT JOIN (select id_client, Max(id) id -- this assumes that a loan with a later create date will also have a higher id.
from loan
group by id_client) il
on il.id_client = c.id
inner join loan l
on l.id = il.id
GROUP BY k.id DESC -- Dont know what "k" is
ORDER BY c.register_date DESC
LIMIT n , m; (n,m is from pagination)

Related

SQL result addition

I have database with table :
Loan
Document
DocumentTemplate
Document is having loanId and documentTeplateId as foreign key.
Every loan has multiple documents.
I want to select every loan (or loanId), that don't have document with teplateId 100.
Currently I'm stuck with this following sql:
SELECT l.id as loanId, d.id as documentId, d.document_templateid as documentTeplateId
FROM loan as l
LEFT JOIN document as d ON (d.loanid = l.id)
WHERE d.document_templateid != 100
ORDER BY loanId DESC
It returns me something like this, obviously..
But that's not what I want.
Any suggestions please?
You need only the distinct loan ids:
SELECT distinct l.id as loanid
FROM loan as l
LEFT JOIN document as d
ON (d.loanid = l.id)
WHERE d.document_templateid != 100
ORDER BY loanId desc
SELECT l.id as loanId
FROM loan as l
LEFT JOIN document as d
ON (d.loanid = l.id)
WHERE d.document_templateid != 100
ORDER BY loanId DESC
GROUP BY loanId
"GROUP BY loanId" will group rows that have the same loanId into one row, removing the duplicates. You can only select loan.id for this to work, which fits well for your scenario since you seem to indicate this is the only value you need.
I think you want aggregation and a having` clause:
SELECT l.id as loanid
FROM loan l LEFT JOIN
document d
ON d.loanid = l.id
GROPU BY l.id
HAVING SUM( d.document_templateid = 100 ) = 0;
If you only want to consider loans that have documents, then the JOIN is not needed:
SELECT d.loanid
FROM document d
GROPU BY d.loanid
HAVING SUM( d.document_templateid = 100 ) = 0;

Fetch only one record from first order by and rest from second order by

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.

mysql "distinct query" from 3 table performs slow on big data

Here is three table, order, order_record, pay, with near 2300000 records.
there will be more than 1 record in pay table when giving 1 order_id, so I need to use DISTINCT to remove repeated result
now I need to get distinct data from those three table join on order_id, the example query sql below:
SELECT
DISTINCT (a.order_id)
a.order_id,a.user_id
b.boss_order_id,
c.pay_id,
FROM order a
LEFT JOIN order_record b ON a.order_id = b.order_id AND b.is_delete IN (0,1)
LEFT JOIN pay c ON a.order_id = c.order_id AND c.is_delete =0 WHERE 1=1 AND a.is_delete IN (0,1)
ORDER BY a.id DESC LIMIT 0, 10
this query will takes plenty of time.
then I change to use "GROUP BY":
SELECT
a.order_id,a.user_id
b.boss_order_id,
c.pay_id,
FROM order a
LEFT JOIN order_record b ON a.order_id = b.order_id AND b.is_delete IN (0,1)
LEFT JOIN pay c ON a.order_id = c.order_id AND c.is_delete =0 WHERE 1=1 AND a.is_delete IN (0,1)
GROUP BY a.order_id
ORDER BY a.id DESC LIMIT 0, 10
this time the query takes 122 seconds.
Is there any faster way to implement?
You are using a left join. Hence, you can do:
SELECT o.order_id, o.user_id, orr.boss_order_id, p.pay_id,
FROM (SELECT o.*
FROM order o
WHERE o.is_delete IN (0, 1)
ORDER BY o.id DESC
LIMIT 10
) o LEFT JOIN
order_record orr
ON o.order_id = orr.order_id AND
orr.is_delete IN (0, 1) LEFT JOIN
pay p
ON o.order_id = p.order_id AND
p.is_delete = 0
WHERE 1=1 AND o.is_delete IN (0, 1)
GROUP BY o.order_id
ORDER BY o.id DESC
LIMIT 0, 10
You are using GROUP BY incorrectly, because you have unaggregated columns in the SELECT that are not in the GROUP BY.
Another approach let a where clause do most the work:
select ...
from order
left join order_using using (order_id)
...
where
order.order_id < (select max(order_id) from orders order by order_id limit 10) ...
limit 10
The final limit 10 is weird though as you may get partial records from an order if you drop the group by. I.e. you probably want to drop it and and just put a limit orders table. With the group by means you will a random data from table b and c unless you use aggregate function to tell mysql which of the row values you want.

mySQL Sub Select needed

I have three tables, libraryitems, copies and loans.
A libraryitem hasMany copies, and a copy hasMany loans.
I'm trying to get the latest loan entry for a copy only; The query below returns all loans for a given copy.
SELECT
libraryitems.title,
copies.id,
copies.qruuid,
loans.id AS loanid,
loans.status,
loans.byname,
loans.byemail,
loans.createdAt
FROM copies
INNER JOIN libraryitems ON copies.libraryitemid = libraryitems.id AND libraryitems.deletedAt IS NULL
LEFT OUTER JOIN loans ON copies.id = loans.copyid
WHERE copies.libraryitemid = 1
ORDER BY copies.id ASC, loans.createdAt DESC
I know there needs to be a sub select of some description in here, but struggling to get the correct syntax. How do I only return the latest, i.e MAX(loans.createdAt) row for each distinct copy? Just using group by copies.id returns the earliest, rather than latest entry.
Image example below:
in the subquery , getting maximum created time for a loan i.e. latest entry and joining back with loans to get other details.
SELECT
T.title,
T.id,
T.qruuid,
loans.id AS loanid,
loans.status,
loans.byname,
loans.byemail,
loans.createdAt
FROM
(
SELECT C.id, C.qruuid, L.title, MAX(LN.createdAt) as maxCreatedTime
FROM Copies C
INNER JOIN libraryitems L ON C.libraryitemid = L.id
AND L.deletedAt IS NULL
LEFT OUTER JOIN loans LN ON C.id = LN.copyid
GROUP BY C.id, C.qruuid, L.title) T
JOIN loans ON T.id = loans.copyid
AND T.maxCreatedTime = loans.createdAt
A self left join on loans table will give you latest loan of a copy, you may join the query to the other tables to fetch the desired output.
select * from loans A
left outer join loans B
on A.copyid = B.copyid and A.createdAt < B.createdAt
where B.createdAt is null;
This is your query with one simple modification -- table aliases to make it clearer.
SELECT li.title, c.id, c.qruuid,
l.id AS loanid, l.status, l.byname, l.byemail, l.createdAt
FROM copies c INNER JOIN
libraryitems li
ON c.libraryitemid = li.id AND
li.deletedAt IS NULL LEFT JOIN
loans l
ON c.id = l.copyid
WHERE c.libraryitemid = 1
ORDER BY c.id ASC, l.createdAt DESC ;
With this as a beginning let's think about what you need. You want the load with the latest createdAt date for each c.id. You can get this information with a subquery:
select l.copyid, max(createdAt)
from loans
group by l.copyId
Now, you just need to join this information back in:
SELECT li.title, c.id, c.qruuid,
l.id AS loanid, l.status, l.byname, l.byemail, l.createdAt
FROM copies c INNER JOIN
libraryitems li
ON c.libraryitemid = li.id AND
li.deletedAt IS NULL LEFT JOIN
loans l
ON c.id = l.copyid LEFT JOIN
(SELECT l.copyid, max(l.createdAt) as maxca
FROM loans
GROUP BY l.copyid
) lmax
ON l.copyId = lmax.copyId and l.createdAt = lmax.maxca
WHERE c.libraryitemid = 1
ORDER BY c.id ASC, l.createdAt DESC ;
This should give you the most recent record. And, the use of left join should keep all copies, even those that have never been leant.

MYSQL select statement - 5 results from each user

I'm trying to do a select statement and it works except that it's not limiting the number of results for each user (U.id) to 5.
SELECT F.id,F.created,U.username,U.fullname,U.id,I.id,I.cached_image
FROM favorites AS F
INNER JOIN users AS U
ON F.faver_profile_id = U.id
INNER JOIN items AS I
ON F.notice_id = I.id
WHERE faver_profile_id IN ('.$users.')
GROUP BY I.id HAVING COUNT(U.id) <= 5
ORDER BY F.faver_profile_id, F.created DESC
I'm grouping by I.id to eliminate duplicates. From my research it looks like you can only use HAVING COUNT if your also grouping by that column, but I cannot group by U.id or I'd lose results rows.
Instead of HAVING, can you slap a LIMIT 5 in there?
Edit: OP cannot LIMIT entire query,
and, AFAIK, MySQL does not support LIMIT in subqueries,
so you can create a temporary table with your five (5) user ids:
create table temp_table ( id INT );
insert into temp_table (id) SELECT U.id FROM users U LIMIT 5;
SELECT F.id,F.created,U.username,U.fullname,U.id,I.id,I.cached_image
FROM favorites AS F
INNER JOIN temp_table AS Ut
ON F.faver_profile_id = Ut.id
INNER JOIN items AS I
ON F.notice_id = I.id
WHERE faver_profile_id IN ('.$users.')
GROUP BY I.id
ORDER BY F.faver_profile_id, F.created DESC;
drop table temp_Table;
Let us know how that works.