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

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

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]

Why INNER JOIN dont not work correct?

I have one SQL query with INNER JOINS. I need to get all offers from table offers.
Table offers is empty now. But the following query returns one row with NULL field.
Why is it returned? How to fix that? I need to return 0 rows if table is empty.
Query:
select *, SUM(offers.price * announcement_product.amount) AS total, announcements.user_id AS creator_ann, announcements.id AS ann_id,
announcements.delivery AS deliveryAnn, announcements.payment AS
paymentAnn, SUM(announcement_product.amount) AS amount,
announcement_product.name as name_product
from `offers`
inner join `announcements` on `announcements`.`id` = `offers`.`announcement_id`
inner join `announcement_product` on `offers`.`announcement_product_id` = `announcement_product`.`id`
inner join `countries` on `countries`.`id` = `announcements`.`country`
where `offers`.`user_id` = 1 and `offers`.`status` = 1 and `offers`.`deleted_at` is null
You're using the aggregate function SUM(), but you don't have any GROUP BY clause.
When you do that you are instructing MySQL to add up all the row values in the column you mention in SUM(). It will do that even if there are no rows to add up.
For best results you should study up on the GROUP BY function and how to use it with SUM(). It's hard to guess what you want from your query.
I'm not sure, but I don't think
select *, ..
when there's multiple tables in the query is valid.
Try
select offers.*,..
This how Your select structure should be :
Select
Id,
Sku,
Sum(Onhand),
Sum(price)
From mytable
Where mytable Onhand > 0
Group by
Id,Sku
If you are going to use aggregate function such as Max,Sum,Min,....
you need to use group by for other table fields that your using in the select part.

how to combine two tables and count their values as one?

I want to get the total numbers of committed crimes when combining the two tables.
But I want to count the numbers for each crime being committed and also display the values of those that has not being committed as 0, How can i achieve this using mysql?
my code:
SELECT count(offense_id)
AS totalnumber,(
select offense_description
from offense
where offense.offense_id = case_crime.offense_id
)as crimeName
from case_crime
group by offense_id
To get a list of all your offenses and the count of registered crimes, you need to use the LEFT JOIN between the two tables .... something like this SQL:
SELECT a.offense_id, a.offense_description, count(b.crime_caseid) as total
FROM offense a LEFT JOIN case_crime b
ON a.offense_id = b.offense_id
group by a.offense_id;
Here is a SQLFiddle to play around with :)
You are looking for a LEFT OUTER JOIN
Something like
SELECT offense.offense_id
, offense_description
, count(case_crime.case_id) as Total_Number
from offense
LEFT OUTER JOIN case_crime ON offense.offense_id = case_crime.offense_id
group by offense.offense_id
I'll admit, I'm a TSQL guy, so I would handle the COUNT(*) returning null when there are no cases with the specified offense using: ISNULL(COUNT(case_crime),0)
Other SQL variants might use COALESCE( COUNT(case_crime), 0)

MySQL Query, multiple counts and sums

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(*).

Mysql: Unable to fetch value from a select query inside a query

I have the following query. If I run it I get this error message.
Query-
SELECT account_name,ABC,date FROM entries
LEFT JOIN accounts ON accounts.id = entries.accounts_id
LEFT JOIN voucher ON voucher.id = entries.trans_id
WHERE trans_id IN ( SELECT trans_id, amount AS ABC FROM entries
WHERE accounts_id='$accounts_id' AND side='C')
AND accounts_id!='$accounts_id' AND side='D'
AND voucher.date between '$dateragne1' AND '$dateragne2'
I think the problem is with the value ABC. It is unable to fetch the value from the second query.
Could you please tell me how to fix this query?
Thanks in Advance :)
Try this:
SELECT account_name, _inner.ABC, date
FROM
(
SELECT amount AS ABC FROM entries
WHERE accounts_id='$accounts_id' AND side='C'
) AS _inner, entries
LEFT JOIN accounts ON accounts.id = entries.accounts_id
LEFT JOIN voucher ON voucher.id = entries.trans_id
WHERE trans_id IN
(
SELECT trans_id FROM entries WHERE accounts_id='$accounts_id' AND side='C'
)
AND accounts_id!='$accounts_id' AND side='D'
AND voucher.date between '$dateragne1' AND '$dateragne2'`
Notes:
Using subquery like this doesn't allow you to request a fields from it.
Also, IN statement use data from only only column, not two.