MySQL Query, multiple counts and sums - mysql

I have a MySQL query that outputs to a php table but I'm having issues in joining two tables that both use a COUNT:
$query = "SELECT mqe.registration,
COUNT(*) AS numberofenqs,
COUNT(DISTINCT ucv.ip) AS unique_views,
SUM(ucv.views) AS total_views
FROM main_quick_enquiries AS mqe
LEFT OUTER JOIN used_car_views AS ucv
ON ucv.numberplate = mqe.registration
WHERE mqe.registration IS NOT NULL
GROUP BY mqe.registration ORDER BY numberofenqs DESC";
The query runs, but the number within the numberofenqs column is always wrong as i know from performing that query on its own that it comes in with the correct result:
SELECT registration, COUNT(*) AS numberofenqs FROM main_quick_enquiries GROUP BY registration ORDER BY numberofenqs DESC
Why is the COUNT(*) not working correctly in top query code and where is it getting the figures from?

it could be because of LEFT OUTER JOIN ...
Try to run this:
SELECT registration
, count(*)
FROM main_quick_enquiries
GROUP BY registration
and compare it with this result
SELECT mqe.registration
, count(*)
FROM main_quick_enquiries mqe
LEFT OUTER JOIN used_car_views ucv
ON ucv.numberplate = mqe.registration
GROUP BY mqe.registration
There could be a problem :) in duplicity rows... try to find one specific registration number, and compare the details of both query
SELECT *
FROM main_quick_enquiries
WHERE registration = XXXX
+
SELECT *
FROM main_quick_enquiries mqe
LEFT OUTER JOIN used_car_views ucv
ON ucv.numberplate = mqe.registration
WHERE registration = XXXX
you should see the diffs

Thanks All, but I think I've nailed it with COUNT(DISTINCT mqe.id) instead of COUNT(*).

Related

select count with another select and inner join

Is it possible to use two "select" in the same query?
I tried it but got the syntax error several times.
My query example:
SELECT
comp.id,
comp.document,
comp.dateStart,
comp.companyName,
comp.fantasyName,
comp.legalNature,
comp.mainActivity,
comp.situation,
comp.shareCapital,
comp.idCompanyStatus,
pp.userCredentialId,
uc.name,
cs.name AS 'nameStatus',
cs.color AS 'colorStatus',
cs.description,
comp.idPurchasedProduct,
comp.actived,
comp.createAt,
comp.updateAt,
comp.phone
FROM `PurchasedProduct` pp
INNER JOIN
`Company` comp on comp.idPurchasedProduct = pp.id
INNER JOIN
`UserCustomer` uc on pp.userCredentialId = uc.credentialId
INNER JOIN
`CompanyStatus` cs on cs.id = comp.idCompanyStatus
WHERE
comp.actived = 1
LIMIT 0,5;
SELECT COUNT(id) AS totalItems, CEILING(COUNT(id) / 10) AS totalPages FROM Company;
I would like the result shown to be all queries on the screen.
Basically, what I want is that the result shown when executing the query is the first and second "select" together.
I really don't know how or don't understand how to do this.
Example:
first result with seconde result
I want to show both results at once.
The documents is fake, not real. Only for demo.
You should be able to do by having the second query as its own JOIN query. Since there is no group by, it is only returning a single row. By no join condition, the value will be available for every row otherwise. So you SHOULD be able to get by doing
select
[ all your other columns ],
JustCounts.TotalItems,
JustCounts.TotalPages
from
[PurchasedProduct and all your other joins]
JOIN ( SELECT
COUNT(id) AS totalItems,
CEILING(COUNT(id) / 10) AS totalPages
FROM Company ) as JustCounts
where
[rest of your original query]

Mysql - I have 3 unique tables, need a hint on getting the details with the count

I have 3 tables which are interconnected and i want to select columns from two tables and counts from table 3. If anyone is aware on this, any hint would be appreciated.
Below is the sql i tried, but the count is getting repeated
SELECT distinct p.p_id, p.p_f6, p.p_l4,m.m_id, (
SELECT COUNT(*)
FROM ttokens t where t.pdetail_id = p.pdetail_id
) AS token_count
FROM tparking p,ttokens t LEFT join ttokens_md m ON t.trefn_id = m.trefn_id
WHERE t.pdetail_id = p.pdetail_id
You can try to use JOIN with subquery to get your count instead of selcet subquery.
SELECT p.p_id, p.p_f6, p.p_l4,m.m_id,t.cnt
FROM tparking p
JOIN (
SELECT pdetail_id,COUNT(*) cnt
FROM ttokens
GROUP BY pdetail_id
) t ON t.pdetail_id = p.pdetail_id
LEFT join ttokens_md m ON t.trefn_id = m.trefn_id
Note
I would use JOIN instead of , comma with where condition to connect two tables,, is an old style.

LEFT JOIN SUM with WHERE clause

The following query always outputs SUM for all rows instead of per userid. Not sure where else to look. Please help.
SELECT * FROM assignments
LEFT JOIN (
SELECT SUM(timeworked) AS totaltimeworked
FROM time_entries
) assignments ON (userid = assignments.userid AND ticketid = ?)
WHERE ticketid = ?
ORDER BY assigned,scheduled
If you want to keep the SELECT *, you would have to add a group by clause in the subquery. Something like this
SELECT * FROM assignments
LEFT JOIN (
SELECT SUM(timeworked) AS totaltimeworked
FROM time_entries
GROUP BY userid
) time_entriesSummed ON time_entriesSummed.userid = assignments.userid
WHERE ticketid = ?
ORDER BY assigned,scheduled
But a better way would be to change the SELECT * to instead select the fields you want a add a group by clause directly. Something like this
SELECT
assignments.id,
assignments.assigned,
assignments.scheduled,
SUM(time_entries.timeworked) AS totalTimeworked
FROM assignments
LEFT JOIN time_entries
ON time_entries.userid = assignments.userid
GROUP BY assignments.id, assignments.assigned, assignments.scheduled
Edit 1
Included table names in query 2 as mentioned in chameera's comment below

Display results between dates sql

I am wanting to display results where the date stored in the table is not between the dates specified in the query.
Here is the current SQL query
SELECT accounts_cstm.statusdescription_c,
users.user_name,
accounts.name,
accounts_cstm.account_number_c,
DATE_FORMAT(MAX(calls.date_modified),'%Y/%m/%d')
FROM accounts
LEFT OUTER JOIN calls ON accounts.id = calls.parent_id
LEFT OUTER JOIN users ON accounts.assigned_user_id = users.id
LEFT OUTER JOIN accounts_cstm ON accounts.id = accounts_cstm.id_c
AND accounts.deleted <> 1
WHERE
(SELECT DATE_FORMAT(MAX(calls.date_modified),'%Y/%m/%d')
FROM calls) NOT BETWEEN '2014/06/25' AND '2014/07/02'
AND users.user_name = 'CBennet'
AND accounts_cstm.chkcustomer_c = '1'
GROUP BY accounts.name
I get a full list of results but I get results that shouldn't appear ie results with calls.date_modified that is in between the dates specified.
See below for an example of a wrong result, you can see that the date to the right is in between the dates 2014/06/25 and 2014/07/02 therefore this shouldn't appear.
Can someone let me know what i'm doing wrong here?
Within the table calls, date_modified is stored in the following format 2014-06-10 10:55:47
try this
SELECT *
FROM `test`
WHERE (date NOT BETWEEN '2012-01-30 14:15:55' AND '2014-09-29 10:15:55')
I created test table with some test values at sqlfiddle and got desired output http://sqlfiddle.com/#!2/5ffb7/4

MySQL: How to subtract results of a JOIN from another query?

I need to exclude the results from a complex query from another query. I don't know how to make a LEFT JOIN work with the results of another JOIN query.
I want to return fields from lt.contacts after subtracting (excluding) the result of this:
(SELECT `contacts`.`idContacts` AS id, `contacts`.`First_Name`, `contacts`.`Last_Name`
FROM `lt`.`contacts`
JOIN `lt`.`groups`
JOIN `lt`.`groups_has_contacts`
ON Contacts_idContacts=idContacts
WHERE idGroup
IN (35)
AND Groups_idGroup
IN (35))
From the results of this:
SELECT * FROM `lt`.`groups_has_contacts` Where `Groups_idGroup` = 37)
I'm pulling my hair out -- any help before I am bald would be appreciated!
Try this:-
SELECT contacts.idContacts, contacts.First_Name, contacts.Last_Name
FROM contacts, groups
where contacts.idContacts=groups.idgroup
OR
SELECT contacts.idContacts, contacts.First_Name, contacts.Last_Name
FROM contacts INNER JOIN groups ON contacts.idContacts=groups.idgroup