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
Related
I'm still learning the MySQl.
This is the relational DBMS :
CUSTOMER (CustID, CustName, AnnualRevenue)
TRUCK (TruckNumber, DriverName)
CITY (CityName, Population)
SHIPMENT (ShipmentNumber, CustID, Weight, Year, TruckNumber, CityName)
Now, I have to formulate for these two queries:
Total weight of shipments per year for each city.
Drivers who drove shipments to London but not Paris.
These are the queries i have came up with:
1.
select sum(s.weight), s.year , c.city
from shipment s, city c
INNER JOIN CITY
on s.CityName = c.CityName
You are mixing and old way to JOIN table (which you should avoid because the joining columns are not explicitly stated and it is confusing for others):
FROM shipment s, city c
You should group columns in the select that are not aggregated (year, city). Also it is better to use an alias for the aggregated column (AS total_weight)
select sum(s.weight) AS total_weight, s.year , c.city
from shipment s
INNER JOIN CITY as c
on s.CityName = c.CityName
GROUP BY s.year, c.city
Try to solve the second query and come back if you have a problem.
Let's say I have the following query to list the average value of a house people own:
SELECT PERSON.NAME, AVG
FROM PERSON, (
SELECT HOUSE.PID AS PID, AVG(HOUSE.VALUE) as AVG
FROM HOUSE
GROUP BY PID
) HOUSES
WHERE PERSON.PID = HOUSES.PID OR PERSON.ID NOT IN (
SELECT PID
FROM HOUSE
)
The query does what I want it to do, except it doesn't include the people who don't have any houses, who should have "0" as their house cost average.
Is this possible, or am I way off?
Simple rule: Never use commas in the FROM clause. Always use explicit JOIN syntax. For instance, in this case, you want a LEFT JOIN, but cannot express it.
SELECT p.NAME, AVG_VALUE
FROM PERSON p LEFT JOIN
(SELECT PID , AVG(VALUE) as AVG_VALUE
FROM HOUSE
GROUP BY PID
) h
ON p.PID = h.PID;
If you want 0 instead of NULL, use COALESCE(AVG_VALUE, 0) as AVG_VALUE in the outer query.
You should use left join, that way records that appear in persons table and dont have corresponding records in houses table will grt nulls on the columns from houses
Tables in my database: 1. Employee
2.Aircraft
3.Certified
Query: I need to find pilot name, eid, aircraft name, cruising_range where pilot is certified to fly more than 3 aircraft's . i wrote a query and it works but i want to know if there is a simple way to achieve this because my query seems much complicated .
My query is :
Edit: Corrected the name of tables.
If you can assume that each AID in Certified had a corresponding value on Aircraft, then it can be done like this:
SELECT ename,employee.eid,aname,crusing_range
FROM employee JOIN certified
ON employee.eid = certified.eid
JOIN aircraft
ON certified.aid = aircraft.aid
WHERE exists(select 1 FROM certified t
WHERE t.eid = employee.eid
GROUP BY t.eid HAVING COUNT(*) >= 3)
Ahh man, don't prefix your columns with your table names. Just have employee ID column as id not eid
I would try this:
SELECT <columns>
FROM aircraft A
LEFT JOIN employee E ON E.eid = A.eid
LEFT JOIN certified C ON C.aid = A.aid
Where SUM(A.eid) > 3
I'm on mobile but I hope it helps.
The key information is in the Aircraft table so start with that and then join the tables you want the extra bits from. Chucking a distinct on employee id within the SELECT will stop duplicates too.
Rethink table names too.
I am looking for customer names of customers who have an interest in all artists.
I understand that in relational algebra, I can use the division operator, however I do not understand the SQL format in doing so.
I have these tables with columns:
customer (customerID, firstname, lastname)
artist (artistID)
customer_interest_in_artists (artistID, customerID)
How would I go about doing this?
You could do this using a simple MIN() construct:
SELECT c.firstname, c.lastname, MIN(ci.customerID IS NOT NULL) AS interest_all
FROM artist
LEFT JOIN customer_interest_in_artists ci USING (artistID)
LEFT JOIN customer c USING (customerID)
GROUP BY c.customerID
HAVING interest_all = 1
You could either:
Identify the customers for whom the number of rows in the customer_interest_in_artists table is equal to the number of rows in the artists table.
or
Identify the customers for whom there does not exist a row in the customer_interest_in_artists table for one or more artists.
The first option os probably easiest to implement, as you can already probably get the number of rows per customer (hint: join, count(*), and group) and compare the number per customer with the number of rows in artists -- hint: having count(*) = (a subquery)
for ORACLE, I use this...
but i don't think mine is the most elegant of all answers, anyway, here it is!
SELECT c.FIRSTNAME, c.LASTNAME, c.CUSTOMERID
FROM DTOOHEY.CUSTOMER c, DTOOHEY.CUSTOMER_ARTIST_INT cai
WHERE c.CUSTOMERID = cai.CUSTOMERID
AND c.CUSTOMERID IN
(SELECT cai.CUSTOMERID
FROM DTOOHEY.CUSTOMER_ARTIST_INT cai
GROUP BY cai.CUSTOMERID
HAVING COUNT (*) = (SELECT COUNT (*) FROM DTOOHEY.ARTIST)
)
GROUP BY c.FIRSTNAME, c.LASTNAME, c.CUSTOMERID;
based on my limited knowledge, the flow of command is:
1) I am trying to get the customer ID, first name and last name of customer
2) I am getting it from the 2 tables (cai and c)
3) trying to join the 2 tables to give me a single data set
4) where the c.customerid is to be gathered in...
this is where the magic begins!!!
5) select the customerID (the single CustomerID)
6) from this table cai
7) group the result based on customerID, this is what gives the single CustomerID Value that you need...
8) having COUNT (*) - having the count of customerID value, to that of equal of the number of count of artists in the dtoohey.artist table.
the main logic is that the number of artist in the artist table (which is 11), exist in the CUSTOMER_ARTIST_INT in the same quantity. As such, we can tally the result of count from the ARTIST Table into the CUSTOMER_ARTIST_INT table.
I think these will useful to you
SELECT a.customerID, c.artistID from customer a
join customer_interest_in_artists b on a.customerID = b. customerID
join artist c on c.artistID = b.artistID
Thank you.
I'm trying to clean a db with duplicate records. I need to move the reference to a single record and delete the other one.
I have two tables: Promoters and Venues, each has a reference to a table called cities. The problem is that there are cities with the same name and different ids, that have a relation with venues and promoters.
With this query I can group all promoters and venues with a single city record:
SELECT c.id as id, c.name as name, GROUP_CONCAT( DISTINCT p.id ) as promoters_ids, GROUP_CONCAT( DISTINCT v.id ) as venues_ids
FROM cities as c
LEFT JOIN promoters as p ON p.city_id = c.id
LEFT JOIN venues as v ON v.city_id = c.id
WHERE c.name IN ( SELECT name from cities group by name having count(cities.name) > 1 )
GROUP BY c.name
Now I want to run an UPDATE query on promoters, setting the city_id equals to the result of the query above.
Something like this:
UPDATE promoters AS pr SET pr.city_id = (
SELECT ID
FROM (
SELECT c.id as id, c.name as name, GROUP_CONCAT( DISTINCT p.id ) as promoters_ids
FROM cities as c
LEFT JOIN promoters as p ON p.city_id = c.id
WHERE c.name IN ( SELECT name from cities group by name having count(cities.name) > 1 ) AND pr.id IN promoters_ids
GROUP BY c.name
) AS T1
)
How can I do this?
Thanks
If I understand correctly, you want to remove duplicate cities (in the end), so you need to update promoters that are linked to any of the cities you want to remove in that process.
I think it makes sense to use the lowest ID of any of the cities with the same name (could be the highest just as well, but I want to specify it at least, and don't leave it up to me.
So in order get the right ID for a promoter, I need to: Select the lowest ID of all cities that have the same name as the city already linked to a promoter.
Fortunately, that demand fits snuggly into a query:
UPDATE promoters AS pr
SET pr.city_id = (
SELECT
-- Select the lowest ID ..
Min(c.id)
FROM
-- .. of all cities ..
Cities c
-- .. that have the same name ..
INNER JOIN Cities pc on pc.Name = c.Name
WHERE
.. as the city already linked to the promoter being updated
pc.id = pr.city_id
GROUP BY
c.name)
The trick is to join Cities on itself by name, so you can easily get all cities with the same name. I think you tried the same with the IN clause, but that's a little more complex than it needs to be.
I don't think you need group_concat at all, besides checking if the inned query returns the correct cities indeed, although it doesn't make sense, since you're already grouping on the name. When written like this, you can tell that there should be no way that this can go wrong:
SELECT
-- Select the lowest ID ..
MIN(c.id) AS id,
GROUP_CONCAT(c.name) AS names --< already grouped by this, so why...
FROM
-- .. of all cities ..
Cities c
-- .. that have the same name.
INNER JOIN Cities pc on pc.Name = c.Name
GROUP BY
c.name
I hope I understood the question correctly.