A) users
B) subscribtion
C) package information
I've table where B is a link between A and C , the query selected from A where B has row id for A and join C by B id .
Full example :
SELECT a.*,c.packageTitle
FROM users AS a
LEFT JOIN subscribe AS b ON (b.userid = a.userid)
LEFT JOIN package AS c ON (b.packageid = c.packageid)
my problem if user has multi subscription in C, i cannot get latest subscription row in loop query, i also used MAX(c.packageid) inside SELECT failed also .
Goal : get latest record in B assigned by A id .
any advice is very much appreciated
I don't think you were far off by trying to use MAX() to obtain the record with the latest package ID (which assumes that this ID is an increasing auto-increment column). In my answer below, the subquery identifies the latest package ID for each user record, using a GROUP BY. This subquery is then used to filter the correct records from your original query.
SELECT a.userid, b.*
FROM users AS a
LEFT JOIN subscribe AS b
ON b.userid = a.userid
LEFT JOIN package AS c
ON b.packageid = c.packageid
INNER JOIN
(
SELECT a.userid, MAX(c.packageTitle) AS maxPackageTitle
FROM users AS a
LEFT JOIN subscribe AS b
ON b.userid = a.userid
LEFT JOIN package AS c
ON b.packageid = c.packageid
GROUP BY a.userid
) t
ON a.userid = t.userid AND c.packageTitle = t.maxPackageTitle
As a note, this query would greatly benefit from something called a Common Table Expression (CTE), which is available in other RBDMS such as SQL Server and Oracle. A CTE would make the query much less repetitive and more readable.
This should be simple enough. In Mysql you just as you said put a max on the select along with a group by. So it would look something like:
SELECT username, id_info, ...
FROM
(
SELECT a.username, a.id_info, c.packageTitle, MAX(package_id)
FROM users AS a
LEFT JOIN subscribe AS b
ON b.userid = a.userid
LEFT JOIN package AS c
ON b.packageid = c.packageid
GROUP BY a.username, a.id_info, c.packageTitle
)
Remember to list all columns in the select which are also being grouped, except the one on which you are taking the max, or the query will fail.
Related
Is there a best way to write this query? It is working just fine on workbench but when I run it on JS, it's not returning the right value.
What I want to do is I want to show users the list of all the items based on their filtered settings (basing on selected category's material and design).
Query:
SELECT COUNT(A.id)
FROM tbl_product A
JOIN tbl_product_details B ON A.id = B.prod_id
JOIN tbl_category C ON A.id = C.prod_id
JOIN tbl_material D ON A.id = D.prod_id
JOIN tbl_design E ON A.id = E.prod_id
WHERE C.category_id IN (6) AND (D.material_id IN (15) OR E.design_id IN (39));
I expect the output to be (workbench result):
COUNT(A.id): 42
instead, it's giving me:
COUNT(A.id): 1582
I am guessing that you want:
SELECT COUNT(DISTINCT A.id)
There are probably other ways to phrase the query (notably, using EXISTS), but this is the simplest modification.
I have been trying to figure out a MySQL statement to perform the following.
I have a table with that stores jobs (tbl_jobs).
Another table that stores work scheduling (tbl_schedule) in the form of fixed time slots.
I want the resulting query to show all jobs scheduled today, check if the jobs are already scheduled (timeslot field) and return the earliest time slot.
My timeslots are stored as numbers from 1-8 so I used MIN to get the smallest number.
There can be the same job spanning multiple timeslots.
I tried a code from MySQL INNER JOIN select only one row from second table but I believe I don't understand the query in depth enough to make my own statement for my purposes
SELECT a.*, c.*
FROM tbl_jobs a
INNER JOIN tbl_schedule c
ON a.job_id = c.job_id
INNER JOIN (
SELECT job_id, MIN(timeslot) ts
FROM tbl_schedule
GROUP BY job_id
) b ON c.job_id = b.job_id
WHERE date = '2018-01-05'
This query on returns jobs that are scheduled and the ones that are not scheduled do not show up at all.
Would appreciate if anyone can assist me in where I should go from here? I am at a roadblock so, I decided to post here for help! Thanks in advance!
To get unscheduled job, use the left join
SELECT a.*, c.*
FROM tbl_jobs a
LEFT JOIN tbl_schedule c
ON a.job_id = c.job_id
LEFT JOIN (
SELECT job_id, MIN(timeslot) ts
FROM tbl_schedule
GROUP BY job_id AND
) b ON c.job_id = b.job_id
WHERE date = '2018-01-05'
Given two tables A and B, I want all the records from A where A.Param = "X". I also want a LEFT JOIN on B where B contains records of trials by various A.Ids for various experiments m, n, o...
The records on B have a time stamp as B.TrialTime (DateTime). As the design goes, there can be multiple trials for the same experiment by the same A.Id in B and for the purposes of the LEFT JOIN I need only the latest trial. This is what I came up with:
SELECT A.*, B.Experiment, B.Response, B.Evaluation, MAX(B.TrialTime) FROM A
LEFT JOIN B ON B.UserID = A.ID
WHERE A.Param = "X" GROUP BY concat(B.UserID, B.Experiment)
The problem is, it no longer acts as a LEFT JOIN, i.e. I am not getting all the users from A, even if they don't have any record in B, which is what I need. Any help?
Without access to the specifics of your tables, the problem you face is knowing "the most recent" trial (in table B)
In many rdbms one can use ROW_NUMBER() to solve this problem, but as yet MySQL does not supply that useful function. So you need to do something like this:
SELECT
a.*
, b.*
FROM A
LEFT JOIN
(
SELECT
bb.*
FROM B bb
INNER JOIN
(
SELECT
UserID
, MAX(TrialTime) MostRecent
FROM B
GROUP BY B.UserID
) bmax ON bb.UserID = bmax.UserID
AND bb.TrialTime = bmax.MostRecent
) b ON B.UserID = A.ID
Basically it isn't possible to get the MAX() of some columns, and all the other column values "from that row", at the same time. You need to get the MAX(TrialTime) then join back to the same table to get the appropriate rows.
For comparison, if row_number() was available, this is how it might be done:
SELECT
a.*
, b.*
FROM A
LEFT JOIN
(
SELECT
bb.*
, ROW_NUMBER() OVER (PARTITION BY bb.userid
ORDER BY bb.TrialTime DESC) AS rn
FROM B bb
) b ON B.UserID = A.ID
AND b.rn = 1
By the way, there isn't any specific reason given for using a LEFT [OUTER] JOIN. If you want rows from A that have NO joined data in B, then you would need an outer join, otherwise you should use an INNER JOIN for efficiency.
I have 3 tables each have almost 70,000 data
when i execute select query in which i add one inner join than it works faster.
Following works faster
select A.id from product as A
inner join product_cat as B on A.id=B.mapped_id
OR
select A.id from product as A
inner join product_sup as C on A.id = C.mapped_id
(It works faster for one inner join)
but when i add both inner join in same select query than it works too slower(Does not display data it just show loading label in phpmyadmin)
select A.id
from product as A
inner join product_cat as B
on A.id = B.mapped_id
inner join product_sup as C
on A.id = C.mapped_id
my purpose it only to find out how much record is there in database.
also tried with count function though takes too much time.
Any help will be appreciated,
Thanks,
Use EXPLAIN to analyze performance of the query and identify any missing indexes.
http://dev.mysql.com/doc/refman/5.5/en/using-explain.html
http://dev.mysql.com/doc/refman/5.5/en/explain-output.html
Add your actual query, execution plan printed by EXPLAIN and CREATE TABLE statements of all involved tables to your question if you want to get a specific advice.
Maybe your query is trying to return more than 1 million of result and that is the reason fo the slowness. Maybe you are doing a Cartesian product between tables B and C.
Let's put an example.
Table (A) = (id=1)
Table (B) = (id=1,mapped_id=1),(id=2,mapped_id=1),
(id=3,mapped_id=1),(id=4,mapped_id=1)
Table (C) = (id=1,mapped_id=1),(id=2,mapped_id=1), (id=3,mapped_id=1)
If we do that query with those data it would return 12 rows, all of them with A.id=1
To solve the problem you could try to use a DISTINCT on the SELECT clause or to do a group with the GROUP BYclase, but I think the better solution is to redesing the query depending on your goals.
If you want to use the group by your query will be something like this
select A.id from product as A
inner join product_cat as B on A.id = B.mapped_id
inner join product_sup as C on A.id = C.mapped_id
group by A.id
I have a query that needs the most recent record from a secondary table called tbl_emails_sent.
That table holds all the emails sent to clients. And most clients have several to hundreds of emails recorded. I want to pull a query that displays the most recent.
Example:
SELECT c.name, c.email, e.datesent
FROM `tbl_customers` c
LEFT JOIN `tbl_emails_sent` e ON c.customerid = e.customerid
I'm guessing a LEFT JOIN with a subquery would be used, but I don't delve into subqueries much. Am I going the right direction?
Currently the query above isn't optimized for specifying the most recent record in the table, so I need a little assistance.
It should be like this, you need to have a separate query to get the maximum date (or the latest date) that the email was sent.
SELECT a.*, b.*
FROM tbl_customers a
INNER JOIN tbl_emails_sent b
ON a.customerid = b.customerid
INNER JOIN
(
SELECT customerid, MAX(datesent) maxSent
FROM tbl_emails_sent
GROUP BY customerid
) c ON c.customerid = b.customerid AND
c.maxSent = b.datesent
Would this not work?
SELECT t1.datesent,t1.customerid,t2.email,t2.name
FROM
(SELECT max(datesent) AS datesent,customerid
FROM `tbl_emails_sent`
) as t1
INNER JOIN `tbl_customers` as t2
ON t1.customerid=t2.customerid
Only issue you have then is what if two datesents are the same, what is the deciding factor in which one gets picked?