How can I attack this mySQL query? - mysql

I need to combine two tables.
The first table is People(SSN PRIMARY KEY, fname, lname).
The other table is Cities(name, cityID), where name = "fname lname" i.e. 2 columns of People concatenated with a space between. One person may have multiple cities associated with them, and a city may have more than one person (many - many).
I want to combine the two into a table PeopleCities(SSN, cityID). If no person is found for a city, I need SSN to be 0 for that cityID. My experience is mostly with sqlite rather than mySQL, so I'm not very confident in my query.
Here is my query:
SELECT ISNULL(People.SSN, 0), Cities.cityID
FROM People
FULL OUTER JOIN Cities
ON (Cities.name = CONCAT_WS(" ", People.fname, " ", People.lname) FROM People);

You can use UNION ALL, first to get the people/city pairs that match and then to get the non-matches:
select p.ssn, coalesce(c.cityid, 0)
from people p left join
cities c
on c.name = concat_ws(' ', p.name, p.lname)
union all
select distinct 0, c.cityid
from cities c
where not exists (select 1 from people p where c.name = concat_ws(' ', p.name, p.lname);

Related

SQL: Employee, Manager, City Names

I am super new to SQL, but hoping for some input on the below. In this assignment, we aren't supposed to use PK or FK so everything is cross referenced. I have an EMPLOYEE table with a column for Manager ID as the Employee ID, and a CityID which is referenced to the City table which includes the ID and Name.
I need to pull up the Employee's name, employee's city, manager name and the managers city, the issue I am having is, one the manager has a NULL value in the City, so it is not producing all of the possible results. If there is a NULL value in any of the columns, I want it to show NULL.
Any idea what I could add to allow for NULL values?
Here is the query so far:
SELECT
CONCAT(e.FirstName, ' ', e.LastName) AS 'EmployeeName', c.CityName AS 'EmployeeCity',
CONCAT(m.FirstName, ' ', m.LastName) AS 'ManagerName', ci.CityName AS 'ManagerCity'
FROM
EMPLOYEE e
JOIN
EMPLOYEE m
ON e.ManagerID = m.EmployeeID
JOIN
CITY c
ON e.CityID = c.CityID
JOIN
CITY ci
ON m.CityID = ci.CityID;
JOIN returns all rows from tables where the key record of one table is equal to the key records of another table
INNER JOIN returns only matching tuples/rows if there is a much on the right of he compared tables.
While LEFT OUTER JOIN returns all matching tuples/rows from both compared tables.
I recommend that you use LEFT OUTER JOIN in your case.
In your case, just use concat_ws():
SELECT CONCAT_WS(' ', e.FirstName, e.LastName) AS EmployeeName,
c.CityName AS EmployeeCity,
CONCAT_WS(' ', m.FirstName, m.LastName) AS ManagerName,
ci.CityName AS ManagerCity
CONCAT_WS() ignores NULL values. And as a bonus, won't include the space.
Note: Only use single quotes for string and date constants. Do not use them for column names.
#casscode you need to use a LEFT JOIN in your query, like this:
SELECT CONCAT(e.FirstName, ' ', e.LastName) AS 'EmployeeName',
c.CityName AS 'EmployeeCity',
CONCAT(m.FirstName, ' ', m.LastName) AS 'ManagerName',
ci.CityName AS 'ManagerCity'
FROM EMPLOYEE e
JOIN EMPLOYEE m ON e.ManagerId = m.EmployeeId
LEFT JOIN CITY c ON e.CityId = c.CityId
LEFT JOIN CITY ci ON m.CityId = ci.CityId;

MySQL DATABASE - SQL statement to join join two tables using a third table

I am a little confused with this question. it asks for the following: "Create a single SQL statement that will display all columns from the student and professor tables. You will need to use the student_professor table to set up the joins."
Normally this wouldnt be difficult under the circumstances of just having 2 tables using a related column, but this is asking me to use a 3rd table?
These are the tables
professor, student, student_professor
Columns for 'professor'
ProfessorId, ProfessorProgram, PhoneNo, Age, ProfessorName
Columns for 'student'
studentno, studentprogram, phoneno, age, firstname, lastname
Columns for 'student_professor'
student_professor_id, ProfessorId, StudentNo, Mentor
Not tested, but this should get you started:
SELECT s.*, p.*
FROM professor p, student s, student_professor sp
WHERE sp.professorId = p.proffesorId
AND sp.studentNo = s.studentNo
ORDER BY p.ProfessorName, s.lastname, s.firstname
or
SELECT s.*, p.*
FROM professor p
JOIN student_professor sp ON sp.professorId = p.proffesorId
JOIN student s ON sp.studentNo = s.studentNo
ORDER BY p.ProfessorName, s.lastname, s.firstname

SELECT statement across multiple tables

First off, I am not an SQL coder.
I am trying to select information from 2 different tables in the same database.
Table 1 is called trans and has 3 columns:
CustNumb, DoT, Amount
Table 2 is called cust and has multiple columns:
CustNumb, Name, Address, City, State, Zip, Phone
The SELECT statement that I'm trying to write will pull data from both tables.
SELECT trans.CustNumb
, cust.Name
, cust.City
, cust.State
, trans.DoT
, trans.Amount
, cust.Phone
,
FROM trans
, cust
WHERE CustNumb LIKE 1234
I THINK I need to use a JOIN statement, but I'm sure what kind of a JOIN or the proper syntax.
Thanks for your help!
You do need a JOIN. In fact, you should simply never write , in the FROM clause.
The JOIN you need would appear to be on the common column between the two tables:
SELECT t.CustNumb, c.Name, c.City, c.State, t.DoT, t.Amount, c.Phone
FROM trans t JOIN
cust c
ON t.CustNumb = c.CustNumb
WHERE c.CustNumb = 1234;
In addition, you should understand that LIKE is a string function and 1234 is not a string. Presumably, you just want equality -- so use =.

Multiple result select inside a main select?

I have a n-to-1 relation in MySQL tables.
Houses can have many owners.
I would like to list all owners for a house.
I have tried this:
SELECT id, name, address
,(
SELECT CONCAT(firstname)
FROM owners
WHERE houses_id = houses.id
) AS 'owner_firstname'
FROM houses;
but i get this results
Error Code: 1242
Subquery returns more than 1 row
I would like to have result like this
100 | Liberty House | 200, NY Street | me, myself, Iren
To address your error: you had a sub-query for your select that brought back multiple owners. The query needed to bring back one literal, in your case, the list of names. You can achieve this in MySQL using the GROUP_CONCAT() function to combine the names of owners for a particular house:
SELECT h.id, h.name, h.address, GROUP_CONCAT(o.firstname) AS owner_firstname
FROM houses AS h
INNER JOIN owners AS o ON h.id = o.houses_id
GROUP BY h.id, h.name, h.address
I think you're looking for group_concat:
select id, name, address,
(select group_concat(firstname separator ', ')
from owners where houses_id = houses.id) as 'owner_firstname'
from houses;

MySQL Join Query

I need to query the database by joining two tables. Here is what I have:
Table Town:
id
name
region
Table Supplier:
id
name
town_id
I currently have the following query which outputs all the Towns that belong to a given region:
SELECT id, name FROM Town WHERE region = 'North West';
Now I need to extend this query and create two further queries as follows:
Output the number of Suppliers for each Town
Output only the Towns that have 1 or more Supplier
I am using PHP for my scripts if that helps. I know I may be able to to get this data using PHP but in terms of performance it will probably be better if it is done in MySQL.
EDIT (27/07/10):
I now needs to extend this one last time - there is another table called Supplier_vehicles:
id
supplier_id
vehicle_id
A Supplier can have many Supplier_vehicles. The count (NumSupplier in this case) needs to now contain the total number of suppliers in a given town that have any of the given vehicle_id (IN condition):
SELECT * FROM Supplier s, Supplier_vehicles v WHERE s.id = v.supplier_id AND v.vehicle_id IN (1, 4, 6)
Need to integrate the above query into the existing JOIN query.
Count the number of suppliers.
SELECT t.id, t.name, count(s.id) as NumSupplier
FROM Town t
LEFT OUTER JOIN Suppliers s ON s.town_id = t.id
GROUP BY t.id, t.name
Only towns that have at least one supplier
SELECT DISTINCT t.id, t.name
FROM Town t
INNER JOIN Suppliers s ON s.town_id = t.id
And you are 100% correct, the best place for this is an SQL query.
SELECT t.id, t.name, count(s.id) as NumSupplier
FROM Town t
LEFT JOIN Suppliers s
[WHERE NumSupplier > 1]
GROUP BY t.id