Multiple Join Searching in Database - mysql

I want to fetch the records from database in my ongoing project.
I have 5 Tables; Everyone make profile which is saved in starting four tables then define partner profile. I want to to fetch all the partner name which meets profile.
This is my tables structure:
Basic Info (reg_id, name, gender, dob, martial_status)
Education (id,reg_id,education,college)
Location (id,reg_id,country,state, city)
Other_details (id,reg_id,height, weight)
Partner (id, reg_id, gender, dob, education, college, country, state, city, height, weight,martial_status) [ This is the Main Table]..
So far I tried this but no luck:
SELECT `basic_info`.`reg_id`,
`basic_information`.`dob`,
`other_detail`.`height`,
`location`.`city`,
`education`.`education`
FROM `basic_information`
INNER JOIN(
SELECT *
FROM `patner`
WHERE `patner`.`reg_id`='shi01') `patner`
ON `basic_information`.`martial_status`=`partner`.`martial_status`
AND `basic_information`.`reg_id`!='shi01'
INNER JOIN `education`
ON `patner`.`education`=`education`.`education`
AND `patner`.`education`=`education`.`education`
INNER JOIN `location`
ON `patner`.`city`=`location`.`city`
INNER JOIN `other_detail`
ON `patner`.`bodytype`=`other_detail`.`body_type`
AND `patner`.`skin`=`other_detail`.`skin`
AND `patner`.`height1` <= `other_detail`.`height`
GROUP BY `basic_information`.`reg_id`;

You did some mistakes in writing join conditions. I have tried to fix it. Try this, It should work;
SELECT BI.reg_id, BI.name
FROM basic_info BI
INNER JOIN
Education E ON BI.reg_id = E.reg_id
INNER JOIN
Location L ON BI.reg_id = L.reg_id
INNER JOIN
Other_details OD ON BI.reg_id = OD.reg_id
INNER JOIN
(Select reg_id, martial_status, height, education, city FROM Partner where reg_id = 'Your_ID') P
ON BI.reg_id = P.reg_id
WHERE
BI.marital_status = P.marital_Status
AND E.Education = P.Education
AND L.city = P.City
AND OD.height <= P.Height
AND BI.reg_id <> 'Your_ID';

Related

Is there a method of counting an attribute that is in a GROUP BY clause?

I need have created a select statement to list out all the customers that have been to multiple merchants below.
I want to create another statement to display how many of those customers have been to each merchant.
What is the optimal method of approaching this problem?
Lists out all customers that have been to multiple merchants.
WITH valentinesDayMerchant AS (
SELECT m.MerchantId, m.MerchantGroupId, m.WebsiteName
FROM Merchant m
INNER JOIN OpeningHours oh ON m.MerchantId = oh.MerchantId AND oh.DayOfWeek = 'TUE'
LEFT JOIN devices.DeviceConnectionState AS dcs ON dcs.MerchantId = oh.MerchantId
WHERE MerchantStatus = '-' AND (m.PrinterType IN ('V','O') OR dcs.State = 1 OR dcs.StateTransitionDateTime > '2023-01-23')
)
SELECT DISTINCT ul.UserLoginId, ul.FullName, ul.EmailAddress, ul.Mobile
FROM dbo.UserLogin AS ul
INNER JOIN dbo.Patron AS p ON p.UserLoginId = ul.UserLoginId
INNER JOIN valentinesDayMerchant AS m ON (m.MerchantId = ul.ReferringMerchantId OR m.MerchantId IN (SELECT pml.MerchantId FROM dbo.PatronMerchantLink AS pml WHERE pml.PatronId = p.PatronId AND ISNULL(pml.IsBanned, 0) = 0))
LEFT JOIN (
SELECT mg.MerchantGroupId, mg.MerchantGroupName, groupHost.HostName [GroupHostName]
FROM dbo.MerchantGroup AS mg
INNER JOIN dbo.Merchant AS parent ON parent.MerchantId = mg.ParentMerchantId
INNER JOIN dbo.HttpHostName AS groupHost ON groupHost.MerchantID = parent.MerchantId AND groupHost.Priority = 0
) mGroup ON mGroup.MerchantGroupId = m.MerchantGroupId
LEFT JOIN (
SELECT po.PatronId, MAX(po.OrderDateTime) [LastOrder]
FROM dbo.PatronsOrder AS po
GROUP BY po.PatronId
) orders ON orders.PatronId = p.PatronId
INNER JOIN dbo.HttpHostName AS hhn ON hhn.MerchantID = m.MerchantId AND hhn.Priority = 1
WHERE ul.UserLoginId NOT IN (1,2,100,372) AND ul.UserStatus <> 'D' AND (
ISNULL(orders.LastOrder, '2000-01-01') > '2020-01-01' OR ul.RegistrationDate > '2022-01-01'
)
GROUP BY ul.UserLoginId, ul.FullName, ul.EmailAddress, ul.Mobile
HAVING COUNT(m.MerchantId) > 1
Methods I have tried include adding the merchant name to a group by and displaying the count of the customers, however this does not work as I cannot have anything related to the Merchant in the GROUP BY, or I wouldn't be able to use HAVING clause to identify the customers that have been to multiple merchants. I have also tried selecting all the merchants and counting the distinct customers which doesn't work as it takes into account all the customers, not specifically the customers that have been to multiple merchants only.

Mysql subqueries problem with data retrieved

I'm trying to run a query but my outcome is not what i need.
So the problem is:
A user can be diretor and if this is the case he can see all activities from his department, and he can be user of another department too, in this case not director but only user.
I have 8 departments each with one director, so the following query should give me the activities of the department and the activities of this particular user in other department:
SELECT t1.idAtividade,
t1.idProfessor,
t2.Escola,
t1.Atividade,
t1.Periodo,
t1.Mes,
t1.haveClasses,
t1.DataPrevista,
t1.Destinatarios,
t1.Orcamento,
t1.PdfAtividade,
t1.Avaliacao,
t1.PdfAvaliacao,
t1.idProfessor,
p.Nome,
g.Grupo,
d.Departamento,
p2.Projeto,
t1.idProjeto
FROM atividades AS t1
INNER JOIN professores p on t1.idProfessor = p.idProfessor
INNER JOIN atividadesgrupos ag on t1.idAtividade = ag.idAtividade
INNER JOIN grupos g on ag.idGrupo = g.idGrupo
INNER JOIN departamentosatividades da on t1.idAtividade = da.idAtividade
INNER JOIN departamentos d on da.idDepartamento = d.idDepartamento
INNER JOIN escolas AS t2 ON (t2.idEscola = t1.idEscola)
INNER JOIN anosescolares AS ae ON (t1.idAnoEscolar = ae.idAnoEscolar)
INNER JOIN projetos p2 on t1.idProjeto = p2.idProjeto
WHERE ae.Estado = 1 AND (da.idDepartamento = :id_dpt and ag.idGrupo = :idGrupo)
ORDER BY (t1.idProfessor = :idProfessor) DESC, t1.idProfessor;");
This query is not working because the department have 22 activities but this user (idProfessor) has 5 in this department and 14 more in another department (defined by idGrupo)
I think i will need a subquery right?

I want to Query w3school database

The database is at: http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all . Particulary I want to get the list of customers who placed product orders on July 1996 from Speedy Express Shipping Company and were served by employees: Davolio Nancy and Peacock Margaret. The result should have:
Name of customer, contact, address, city, postal code and country
The orderDetailID they placed
Contacts of the shipping company
Product name, price and quantity
Product name, price and units bought
Category of the products
Here is my query:
SELECT
c.CustomerName,
c.ContactName,
c.Address,
c.City,
c.PostalCode,
c.Country,
o.OrderDetailID,
s.Phone,
r.ProductName,
r.Price,
o.Quantity,
g.CategoryName
FROM Customers c
JOIN Orders d
on (c.CustomerID = d.CustomerID)
LEFT JOIN OrderDetails o
on (o.OrderID = d.OrderID)
LEFT JOIN Shippers s
on (s.ShipperID = d.ShipperID)
LEFT JOIN Products r
on (r.ProductID = o.ProductID)
LEFT JOIN Categories g
on (g.CategoryID = r.CategoryID)
LEFT JOIN Employees e
on (e.EmployeeID = d.EmployeeID)
WHERE s.ShipperName = 'Speedy Express' AND
((e.LastName = 'Davolio' AND e.FirstName = 'Nancy') OR
(e.lastName = 'Peacock' AND e.firstName = 'Margaret')) AND
EXTRACT(YEAR_MONTH FROM d.OrderDate) = 199607;
I get error which says:
ERROR 1: Could not prepare statement (1 near "FROM": syntax error)
When I remove the last condition (of extracting the date) as follows:
SELECT c.CustomerName, c.ContactName, c.Address, c.City, c.PostalCode, c.Country, o.OrderDetailID, s.Phone, r.ProductName, r.Price, o.Quantity, g.CategoryName FROM Customers c JOIN Orders d on (c.CustomerID = d.CustomerID) LEFT JOIN OrderDetails o on (o.OrderID = d.OrderID) LEFT JOIN Shippers s on (s.ShipperID = d.ShipperID) LEFT JOIN Products r on (r.ProductID = o.ProductID) LEFT JOIN Categories g on (g.CategoryID = r.CategoryID) LEFT JOIN Employees e on (e.EmployeeID = d.EmployeeID) WHERE s.ShipperName = 'Speedy Express' AND((e.LastName = 'Davolio' AND e.FirstName = 'Nancy') OR (e.lastName = 'Peacock' AND e.firstName = 'Margaret'));
the error disappears. So please how can i fix the year_month condition without getting error!
One possibility here is that your version of MySQL, for whatever reason, does not support YEAR_MONTH being used with EXTRACT(). One workaround here would be to use DATE_FORMAT() instead:
WHERE DATE_FORMAT(d.OrderDate, '%Y%m') = '199607'
To test whether you have an old version of EXTRACT(), just try running the following simple query:
SELECT EXTRACT(YEAR_MONTH FROM NOW());
If this errors out, then my conjecture is correct.

Show names from two values

I am trying to get a SQL code but can't really figure out how to do it so I will explain what I want.
I have 4 tables called Person, Customer, Adres and Store. Now I have to show each customer NAMES which lives in the same city as where there is a Store. So First I figured out which persons are customers by:
SELECT person_name
FROM person
WHERE person_id IN
(SELECT Person_Person_Id
FROM customer);
Which stores are in which city:
SELECT Store_name, adres_city
FROM store s, adres a
WHERE s.Adres_Adres_Id = a.adres_id;
Note that person_person_id is the same as person_id just as a fk.
I am stuck at this code and don''t know how to go further from here. My column name of table adres = adres_city.
Okay, if I realised what do you want, try to do this:
select --distinct
b.Adres_City,
a.person_id
from
dbo.Person a
join dbo.Adres b on a.adres_adres_id = b.Adres_Id
join dbo.Customer c on a.person_id = c.Person_Person_Id
join dbo.Store d on b.Adres_Id = d.Adres_Adres_Id
If you are not sure, that all your keys in tables are uniq, uncomment --distinct in the first string.
Or, if you are want to know statistics among your cities, do this:
select
b.Adres_City,
count(distinct a.person_id) as cnt
from
dbo.Person a
join dbo.Adres b on a.adres_adres_id = b.Adres_Id
join dbo.Customer c on a.person_id = c.Person_Person_Id
join dbo.Store d on b.Adres_Id = d.Adres_Adres_Id
group by b.Adres_City
Please let me know, if it will help you.
Update1:
select --distinct
b.Adres_City,
a.person_id
from
dbo.Person a
join dbo.Adres b on a.adres_adres_id = b.Adres_Id
join dbo.Customer c on a.person_id = c.Person_Person_Id
where
b.Adres_City in (
select y.Adres_City
from dbo.Store x join dbo.Adres y on y.Adres_Id = x.Adres_Adres_Id
)

MySql showed me no result with my query

I have 4 tables which are (model, license, pilot, and person)
Model: mid, name
License: mid, pid, licenseDate
Pilot: pid, hireDate
person: pid, firstName, lastName
I want to get the names of pilots who are not licensed to fly any airplane
I tried this query, but it showed me no result!!!
select model.mid, license.pid, license.mid, license.licenseDate, pilot.pid, pilot.hireDate, person.firstName, person.lastName
from model, license, pilot, person
where pilot.pid = license.pid and model.mid = license.mid and pilot.pid = person.pid
and not exists(SELECT null FROM model WHERE pilot.pid = license.pid);
try this... using inner join.
SELECT model.mid, license.pid, license.mid, license.licenseDate, pilot.pid, pilot.hireDate, person.firstName, person.lastName
FROM model
INNER JOIN license ON (model.mid = license.mid)
INNER JOIN pilot ON (pilot.pid = license.pid)
INNER JOIN person ON (pilot.pid = person.pid)
WHERE pilot.pid = license.pid AND model.mid = license.mid AND pilot.pid = person.pid
AND pilot.pid != license.pid);
Not tested the script, but You can fetch pilots which are not in License table means they're not licensed to fly a plane, then you can join the result with person table to fetch the particular name.
select p.firstname, p.lastname
from
(
select pid from pilot
where not exists (select pid from License where License.pid = pilot.pid)
) DT
inner join person p
on p.pid = DT.pid
Give this a try:
SELECT pe.firstName, pe.lastName FROM pilot p
LEFT JOIN license l ON p.pid = l.pid
JOIN person pe ON p.pid = pe.pid
WHERE l.pid IS NULL