sql count(*) query on results of another query performing multiple results - mysql

how to perform sql count(*) query on results of another query performing multiple results ?
I've 3 tables :--
user_subscribe table where I've 'user_id' and other columns.
user table where we have 'user_id' & 'country_id' columns where user_id is being linked with user_subscribe table and country_id is being linked with 'country' table.
country table having 'country_id' column.
I need to get total count of user_subscribe based on users (user_id) who belongs to same country.
A Help is highly appreciated as I'm being stuck on this problem from last 7 days.

SELECT COUNT(US.user_id) as country_user_subscribed
FROM user_subscribe as US
LEFT JOIN users as U ON user.id=US.user_id
LEFT JOIN countries as C on C.id=U.country_id
GROUP BY C.country_id

Try This Solution :
SELECT C.CountryName,Count(u.UserId) AS UserCount FROM User_Subscribe AS us
LEFT JOIN User AS u ON us.UserId = u.UserId
LEFT JOIN Country AS c ON u.CountryId = c.CountryId
WHERE c.CountryId = 3
GROUP BY c.CountryName

Related

How can I get customer data based on the number of users they have?

I want to get customer data from all the businesses with more than 1 user.
For this I think I need a subquery to count more than 1 user and then the outer query to give me their emails.
I have tried subqueries in the WHERE and HAVING clause
SELECT u.mail
FROM users u
WHERE count IN (
SELECT count (u.id_business)
FROM businesses b
INNER JOIN users u ON b.id = u.id_business
GROUP BY b.id, u.id_business
HAVING COUNT (u.id_business) >= 2
)
I believe that you do not need a subquery, everything can be achieved in a joined aggregate query with a HAVING clause, like :
SELECT u.mail
FROM users u
INNER JOIN businesses b on b.id = u.id_business
GROUP BY u.id, u.email
HAVING COUNT (*) >= 2
NB : in case several users may have the same email, I have added the primary key of users to the GROUP BY clause (I assumed that the pk is called id) : you may remove this if email is a unique field in users.

MySQL Query phpmyadmin

I'm trying to make a SQL query that will search for user id and populate the query with the username.
These are my tables:
Table Names: 'users' and 'schedule'
This is how I want it to look like, where 'schedule' table now shows the username instead of the user's ID
This is the query you are looking for:
SELECT s.REFID, s.jobnum, s.customer, u1.username AS engineer, u2.username AS sales
FROM schedule s, users u1, users u2
WHERE s.engineer=u1.id
AND s.sales=u2.id
You need to reference the users table two separate times, since you are checking in one sub-query for the engineer's username, and then checking in a separate sub-query for the salesperson's username.
Here is a link to an SQLFiddle that shows the result of the query's execution. It matches up with what you were looking for. I hope this helps.
Following Query will give you the expected result:
SELECT
s.refid as refid,
s.jobnum as jobnum,
s.customer as customer,
u_engg.username as engineer,
u_sales.username as sales
FROM
user u_engg join schedule s on u.id = s.engineer join
user u_sale on u_sale.id = s.sales
SELECT s.refid, s.jobnum, s.customer, u.username engineer, u.username sales
FROM schedule s
LEFT OUTER JOIN users u
ON s.engineer = u.id AND s.sales = u.id
It looks like you need to reference the users table two times. One JOIN to get the engineer username, and a second JOIN to get the sales username.
Something like this:
-- return all rows from schedule, and lookup of username where available
SELECT s.REFID
, s.jobnum
, s.customer
, e.username AS engineer
, a.username AS sales
FROM schedule s
LEFT
JOIN users e
ON e.id = s.engineer
LEFT
JOIN users a
ON a.id = s.sales
Using a LEFT [OUTER] JOIN ensures that the rows from schedule will be returned when there isn't a matching row in the users table. For example, if you had a NULL in the sales column of a row in schedule, there wouldn't be a matching row in the users table. With an [INNER] JOIN, the row from schedule would not be returned. But the query above does return the row, but with a NULL for the username when matching rows are not found.
If the engineer and sales columns are defined as NOT NULL, and foreign keys are defined and enforced, then the LEFT keyword can be omitted from the query above. In the more general case, where foreign keys are not enforced (e.g. MyISAM) or not defined, or the columns are nullable, we'd generally want the LEFT keywords.
UPDATE
Removing the LEFT keywords from the query will produce a query equivalent to that in the answer from Alvin Lee, which implements INNER JOIN operations.
The query from Alvin Lee will EXCLUDE rows from schedule that have a value in the engineer or sales column that is NULL, or has a value that does not match a value found in the id column of the users table.
To identify if any rows in the schedule table are not being returned by the query using an INNER JOIN, you can run a query that does an anti-join pattern.
-- find rows in schedule that don't have matching row in users
SELECT s.REFID
, s.jobnum
, s.customer
, s.engineer
, s.sales
FROM schedule s
LEFT
JOIN users e
ON e.id = s.engineer
LEFT
JOIN users a
ON a.id = s.sales
WHERE a.id IS NULL
OR e.id IS NULL
try this:
select sc.REFID, sc.jobnum, sc.customer, us.username as engineer, us.username as sales
from schedules as sc
left join users as us on sc.engineer = us.ID and sc.sales = us.ID

mysql join to exclude missing entries

I have two tables and I want to display all records from the first table where the field that joins them is not present in the second table.
$sql = "SELECT d.*,t.id from `donations` d
JOIN `teams` t
ON d.teamid = t.id
WHERE t.id IS NULL";
In other words I want to join donations and teams. But I want to retrieve only the records from donations where the team field is not present in the teams table.
The above displays zero records and is not doing the trick.
Thanks for any suggestions.
SELECT d.*,t.id from `donations` d
LEFT OUTER JOIN `teams` t
ON d.teamid = t.id
WHERE t.id IS NULL
You could use a sub query.
select * from donations
where teamid not in (
select id from teams
)
That should select all donations which has a teamid which is not present in the teams table.

COUNT via multi-chain join

I have this hierarchy in my database (from lowest to highest):
User => Dept => Area => Company
Now I need to make a table that shows all companies (some info about them taken directly from companies table) but the last column in the HTML table I want to be Number of users. I know I need to join the tables together and perhaps join table to itself, but how do I do this?
Each of these tables have a column linking to its parent table (except Company ofc).
JOIN the tables:
SELECT
c.companyId,
c.CompanyName,
IFNULL(COUNT(u.userID), 0) AS 'Number Of Users'
FROM Company AS c
LEFT JOIN Area AS a ON c.CompanyID = a.CompanyID
LEFT JOIN Dept AS d ON a.DeptId = d.DeptId
LEFT JOIN users AS u ON D.UserId = u.UserId
GROUP BY c.companyId,
c.CompanyName;
Note that: LEFT JOIN with IFNULL will give you those companies that has no matched rows in the other tables; with count zero in this case

How to search when joining 3 tables but exclude result for one of them?

I've been tying for hours now to get a particular result and haven't found any answer on the web - and as I'm not an SQL expert at all, I'm asking a question here.
I have 3 tables: user (id, name...), cars (id, type, color, engine power...) and an intermediary table to save all the scores users gave to the car: scores (id, user_id, car_id, score).
I'm trying to find a query that could return for one particular user, all the cars that he hasn't rated yet. I've tried the following but it returns null:
$q=mysql_query("SELECT * FROM cars LEFT OUTER JOIN scores ON cars.id = scores.car_id WHERE scores.user_id != ('".$userId."')");
Does someone have a clue?
SELECT
*
FROM
cars
WHERE
NOT EXISTS (SELECT 1 FROM scores WHERE car_id = cars.id AND user_id = ?)
where ? is the ID of that particular user.
A composite index in scores over (car_id, user_id) is useful here.
You can use your code with small modification:
SELECT * FROM cars
LEFT OUTER JOIN scores ON cars.id = scores.car_id and scores.user_id=".$userId."
WHERE scores.id IS NULL
SELECT * FROM
car c
WHERE c.id NOT IN (
SELECT s.car_id
FROM score s, user u
WHERE u.id = s.user_id
AND u.id = ?
)