Output Name Field is DIfferent With the Output without Name Field MYSQL - mysql

SELECT users.id as uid, projects.id as pid
FROM users
inner join usergroup on usergroup.id = users.user_group
inner join bookings on bookings.agent_id = users.id
inner join units on bookings.unit = units.id
inner join types on types.id = units.types_id
inner join projects on projects.id = types.project_id
WHERE bookings.status = 'Accepted' AND units.status = 'Sold'
GROUP BY pid
with the query above, i get the correct and logic output:
pid | uid
1 1
2 1
9 12
10 14
then i want to show the user's name, so i added 1 field in query as shown below:
SELECT users.id as uid, users.f_name, projects.id as pid
FROM users
inner join usergroup on usergroup.id = users.user_group
inner join bookings on bookings.agent_id = users.id
inner join units on bookings.unit = units.id
inner join types on types.id = units.types_id
inner join projects on projects.id = types.project_id
WHERE bookings.status = 'Accepted' AND units.status = 'Sold'
GROUP BY pid
but i got a different output for uid:
pid | uid
1 1
2 1
9 9
10 11
This is not logic and anyone know why? Let's assume both are correct but why will output different result?

Your 2nd query you are filtering data with join condition before where condition while in 1st query you are filtering data just in where clause...keep you 2nd query same as 1st to get same results....
try below query-
SELECT projects.id as pid, users.id as uid, users.f_name
FROM users
inner join usergroup on usergroup.id = users.user_group
inner join bookings on bookings.agent_id = users.id
inner join units on bookings.unit = units.id
inner join types on types.id = units.types_id
inner join projects on projects.id = types.project_id
WHERE bookings.status = 'Accepted' AND units.status = 'Sold'
GROUP BY pid

One project ID can be associated to many units and each unit with many bookings and hence with many users. You group by project ID, but you don't specify which of all associated users you want to see for a project ID. You would do this with an aggregate function such as MIN(users.id), MAX(users.id), etc. But you don't use such function, thus telling MySQL: "just give me randomly one of the matching users".
As long as you keep your query as is, it seems that MySQL always gives you the same users, maybe the first it finds. This is by no way guaranteed; you could just as well get different users with the same query.
Now that you changed your query, MySQL goes another route and picks different matching users.

Related

How to select more rows based on column id of first select

I have 2 select statements. One returns 2 rows and the other must return more rows. I want to select all of the rows in one single query and not use a UNION because I will not be able to use the same column id with UNION.
My query is this
SELECT SUB.name FROM (SELECT U1.id ,U1.name, UOM.organization_id AS ORGID FROM #_users AS U1
JOIN #_user_organization_map AS UOM ON U1.id = UOM.user_id
JOIN #_rsdirectory_entries AS RSE ON UOM.organization_id = RSE.id
JOIN #_rsmembership_membership_subscribers AS RMS ON U1.id = RMS.user_id
WHERE RMS.membership_id = 66 AND UOM.organization_id = 301) AS SUB
JOIN #_users AS U ON SUB.id = U.id
JOIN #_user_organization_map AS UOM1 ON SUB.id = UOM1.user_id
JOIN #_rsdirectory_entries AS RSE1 ON UOM1.organization_id = RSE1.id
JOIN #_rsmembership_membership_subscribers AS RMS1 ON SUB.id = RMS1.user_id
WHERE UOM1.organization_id = SUB.ORGID;
What i'm trying to do is get all users belonging to a specific membership but not all users carry the membership_id value in their details in the database, only the CEO of the organization.
So, the nested SELECT should get the CEO's name to whom the subscription belongs (hence the membership_id) and then in the outer SELECT I want to get all of the employees under the same organization, by organization ID.
The result I get is the CEO's name twice but I should get the CEO's name and then all of the employees' names.
The subquery is only returning the CEO's information. The information about the employees is in the U table that you join with it.
But you can't join on U.id = SUB.id, because that just restricts U to the CEO's row. You want to get all the users in the same organization as the CEO.
I think this will do it. The last three joins get the organization ID of the CEO
SELECT U.name
FROM #_users AS U1
JOIN #_user_organization_map AS UOM1 ON1 U.id = UOM1.user_id
JOIN #_user_organization_map AS UOM ON UOM1.id = UOM.id
JOIN #_rsdirectory_entries AS RSE ON UOM.organization_id = RSE.id
JOIN #_rsmembership_membership_subscribers AS RMS ON U1.id = RMS.user_id
WHERE RMS.membership_id = 66 AND UOM.organization_id = 301

Showing maximum

I want to show maximum of guarantee which specific user has. For example user has bought 3 items which have 1,2,5 years guarantee. So I want to show 5 years guarantee and name of this product.
I did subquery in case few products have this same guarantee.
SELECT t.`id-user`, name, guarantee FROM transactions t
JOIN user u ON `t`.`id-user` = `u`.`id-user`
JOIN products p ON `p`.`id-product = `t`.`id-product`
WHERE guarantee = (SELECT MAX(p2.guarantee)
FROM products p2
WHERE `p2`.`id-product` = `p`.`id-product`)
This query shows all products and their guarantees.
I think the simplest method is the substring_index()/group_concat() method for getting values associated with a maximum/minimum:
SELECT t.iduser, u.name,
MAX(p.guarantee) as guarantee,
SUBSTRING_INDEX(GROUP_CONCAT(p.name ORDER BY p.guarantee DESC), ',', 1)
FROM transactions t JOIN
user u
ON t.iduser = u.iduser JOIN
products p
ON p.idproduct = t.idproduct
GROUP BY t.iduser, u.name;
You can use your method too, but the correlated subquery is tricky:
SELECT t.iduser, u.name, p.guarantee, p.name
FROM transactions t JOIN
user u
ON t.iduser = u.iduser JOIN
products p
ON p.idproduct = t.idproduct
WHERE p.guarantee = (SELECT MAX(p2.guarantee)
FROM transactions t2 JOIN
products p2
ON p2.idproduct = t2.idproduct
WHERE t2.iduser = u.iduser
);
I think it work.
select [User].Name as [UserName],
Product.MaxGuarantee,
Product.Name as Product_Name
from [Users] [User]
left join Transactions [Transaction]
on [Transaction].[User] = [User].ID
cross apply(
select max(guarantee) MaxGuarantee, Name
from Products
where ID = [Transaction].Product
) Product
where [User].ID = ''

Select Row for Max Sum Value In Multiple Tables MYSQL

I need to query for the users with highest amount of sales by all projects, where the users are in users table, sales in units table, projects in projects table.
Projects Top Agent Total Sales for Project
Project A User A 100000
Project B User B 20000
Project C User A 1000
Project D - 0
The Projects column is list all the projects regardless it has sales or not.
The Top Agent column is list the user with the highest sales in the project.
The Total Sales for Project is the total sales for a projects.
The agent column i got is incorrect because there is someone else has the highest sales, the query seems to return the first row of the result
SELECT projects, pid, CASE WHEN agent is null THEN '-' ELSE agent END as agent,
CASE WHEN FORMAT(topagent,0) > 0 THEN FORMAT(topagent,0) ELSE 0 END as salesvolume
FROM (
SELECT projects.name as projects, projects.id as pid,
concat(users.f_name, ' ', users.l_name) as agent,
SUM(units.price) AS topagent
FROM users inner join bookings on bookings.agent_id = users.id
inner join units on bookings.unit = units.id
inner join types on types.id = units.types_id
inner join projects on projects.id = types.project_id
WHERE units.status = 'Sold'
GROUP BY pid
union
select projects.name as projects, projects.id as pid,
concat(users.f_name, ' ', users.l_name) as agent,
SUM(units.price) AS topagent
from projects left outer join types on projects.id = types.project_id
left outer join units on types.id = units.types_id and units.status = 'Sold'
left outer join bookings on units.id = bookings.unit and units.status = 'Sold'
left outer join users on bookings.agent_id = users.id and units.status = 'Sold'
group by pid
) a
GROUP BY pid
order by topagent desc
Try it if helps you-
SELECT a.prjname, IFNULL(usr.name,'-') AS Top_Agent, SUM(a.sale) AS Total_Sales_for_Project
FROM
(
SELECT prj.id AS prjid,prj.name AS prjname,usr.id,usr.name AS usrname,IFNULL(SUM(unit.price),0) AS sale
FROM projects AS prj
LEFT JOIN `types` AS typ ON typ.project_id=prj.id
LEFT JOIN units AS unt ON unt.type_id=typ.id AND unt.status='sold'
LEFT JOIN bookings bkg ON bkg.unit=unt.id
LEFT JOIN users usr ON usr.id=bkg.agent_it
GROUP BY prj.id,usr.id
ORDER BY prj.id,usr.id,sale DESC
) a
GROUP BY a.prjid
Your column aliases are confusing to read. In English, it seems what you mean by topagent is "sum of sales by a human". But in SQL, your GROUP BY pid means that the SUM(units.price) really means "sum of sales in a project".
Then the UNION adds a list of projects to a list of users. The agent names are basically random at this point.
If I decipher the requirements as "a list of projects ranked by the sales values of each project's top sales agent", then you'd have SQL as below:
SELECT
pid,
projects.name as project_name,
IFNULL(a.top_agent_name,'-') as top_agent_name,
CASE WHEN FORMAT(top_agent_sales,0) > 0 THEN FORMAT(top_agent_sales,0) ELSE 0 END as top_agent_salesvolume
FROM
projects
JOIN
SELECT
a.pid,
a.agent_name as top_agent_name,
a.agent_sales as top_agent_sales
FROM
(SELECT
projects.id as pid,
concat(users.f_name, ' ', users.l_name) as agent_name,
SUM(units.price) AS agent_sales
FROM users
inner join bookings on bookings.agent_id = users.id
inner join units on bookings.unit = units.id
inner join types on types.id = units.types_id
inner join projects on projects.id = types.project_id
WHERE units.status = 'Sold'
GROUP BY pid, users.id
) a # get all agents for all projects
JOIN
(SELECT
MAX(agent_sales) as max_project_agent_sales
FROM
(SELECT
projects.id as pid,
SUM(units.price) AS agent_sales
FROM users
inner join bookings on bookings.agent_id = users.id
inner join units on bookings.unit = units.id
inner join types on types.id = units.types_id
inner join projects on projects.id = types.project_id
WHERE units.status = 'Sold'
GROUP BY pid, users.id
)
GROUP BY pid) b ON a.pid = b.pid
WHERE
a.agent_sales = b.max_project_agent_sales
ORDER BY a.agent_sales desc
Old answer below:
There are 2 topagents for each pid in the inner query since it's a union of 2 group bys. There isn't a reducing function in the outer group by pid so the topagent returned in the select is the first one that came up in the inner query.

MYSQL compare values from same columns

Okay I tried to look all over stackoverflow, and the closest solution I found is this:
mysql AND clause on same column multiple times
But I can't use statements and "having" syntax won't work because of group by. There MUST be a simple solution to this.
The 2 tables looks like this (simplified):
users:
uid name
1 person 1
2 person 2
3 person 3
categories:
uid value
1 actor
1 musician
2 actor
3 dancer
4 musician
4 dancer
I want to get the uid of those that are 2 values at the same time. For example, I want to get the UID that is an actor AND a musician. Not just one value, but both of them must be required!
First I tried this:
SELECT users.uid, users.name
FROM
users
LEFT OUTER JOIN categories ON users.uid = categories.uid
WHERE (categories.value = 'actor' AND categories.value = 'musician')
GROUP BY u.uid;
This of course does not work since one row can't have 2 values.
Does anyone know a solution?
You can JOIN to the categories table multiple times to get the result:
SELECT users.uid, users.name
FROM users
INNER JOIN categories c1
ON users.uid = c1.uid
INNER JOIN categories c2
ON users.uid = c2.uid
WHERE c1.value = 'actor'
AND c2.value = 'musician';
See SQL Fiddle with Demo
SELECT users.uid, users.name
FROM users
LEFT JOIN categories ON users.uid = categories.uid
WHERE categories.value in ('actor', 'musician')
GROUP BY u.uid, users.name
having count(distinct categories.value) = 2;
Use a having clause
SELECT u.uid, u.name
FROM users u
LEFT OUTER JOIN categories c ON u.uid = c.uid
WHERE c.value = 'actor' OR c.value = 'musician'
GROUP BY u.uid
having count(distinct c.value) > 1
If you really do not want to use having you could try this:
SELECT uid, name
FROM users
WHERE
uid IN (SELECT uid FROM categories WHERE value='actor')
AND uid IN (SELECT uid FROM categories WHERE value='musician')
But there is really nothing wrong with using HAVING ;)

Complex MySQL query with multiple select statements

I have three tables in Mysql that are link together:
Profile (ID, Name, Stuff..)
Contact(ID, ProfileID,desc,Ord)
Address(ID,ProfileID, desc, Ord)
Now I need to select all profile from the profile table, with the “desc” field from Contact and Address where Ord = 1. (this is for a search function where in a table I’ll display the name, main contact info and main Address of a client.
I can currently do this with three separate SQL request:
SELECT Name, ID FROM Profile WHERE name=”bla”
Then in a foreach loop, I’ll run the other two requests:
SELECT ProfileID, desc FROM Contact WHERE ProfileID=MyProfileID AND Ord=1
SELECT ProfileID, desc FROM Address WHERE ProfileID=MyProfileID AND Ord=1
I know you can do multiple SELECT in one query, is there a way I could group all three SELECT into one query?
You should be able to JOIN the tables on the profile.id and the profileid in the other tables.
If you are sure the profileid exists in all three tables, then you can use an INNER JOIN. The INNER JOIN returns matching rows in all of the tables:
select p.id,
p.name,
c.desc ContactDesc,
a.desc AddressDesc
from profile p
inner join contact c
on p.id = c.profileid
inner join address a
on p.id = a.profileid
where p.name = 'bla'
and c.ord = 1
and a.ord = 1
If you are not sure that you will have matching rows, then you can use a LEFT JOIN:
select p.id,
p.name,
c.desc ContactDesc,
a.desc AddressDesc
from profile p
left join contact c
on p.id = c.profileid
and c.ord = 1
left join address a
on p.id = a.profileid
and a.ord = 1
where p.name = 'bla'
If you need help learning JOIN syntax, here is a great visual explanation of joins
This query below only selects column when an ID from Profile table has atleast one match on tables: Contact and Address. If one or both of them are nullable, use LEFT JOIN instead of INNER JOIN because LEFT JOIN displays all records from the Left-hand side table regardless if it has a match on other tables or not.
SELECT a.*,
b.desc as BDESC,
c.desc as CDESC
FROM Profile a
INNER JOIN Contact b
ON a.ID = b.ProfileID
INNER JOIN Address c
ON a.ID = c.ProfileID
WHERE b.ORD = 1 AND
c.ORD = 1 AND
a.Name = 'nameHERE'
The LEFT JOIN version:
SELECT a.*,
b.desc as BDESC,
c.desc as CDESC
FROM Profile a
INNER JOIN Contact b
ON a.ID = b.ProfileID AND b.ORD = 1
INNER JOIN Address c
ON a.ID = c.ProfileID AND c.ORD = 1
WHERE a.Name = 'nameHERE'
To further gain more knowledge about joins, kindly visit the link below:
Visual Representation of SQL Joins
i have created working demo as your requirement :
The query bellow will retrieve all matching records from the database.its retrieving profile id,name stufff and description of contact tables
select p.id,p.name,p.stauff,c.descr,a.descr from profile as p
inner join contact as c on c.profileid=p.id
inner join address as a on a.profileid=p.id
where p.name="bla" and c.ord=1 and a.ord=1