I am trying to filter my results to only show a person's name who is staying at a hotel in a specific city. What I have so far is
select guestName
from Guest
join Hotels on hotelNo=1
However, when I do this, the result page lists every guest name in the database, rather than the ones that are staying in hotelNo 1.
You should put your condition in Where clause instead.
And Join should look like this
select guestName
from Guest g
join Hotels h on g.HotelId = h.HotelId -- Primary Key of Hotels equals Foreign Key of Guest
where hotelNo = 1
Explanation
In Join clause, You should address the condition between 2 tables (It is often between Primary key (Hotel table) and Foreign Key (Guest table))
More details in https://www.w3schools.com/sql/sql_join_inner.asp
Related
When I use join, by the ON part I write down the connection, foreign key = primary key.
But when I reverse the fk and pk I still get the same result, does this mean that it doesn't matter which one goes first?
Example:
select
movie.title,
director.firstname,
director.lastname
from movie
join director on movie.director = director.directorcode
(This is the one with the right order FK=PK)
select
movie.title,
director.firstname,
director.lastname
from movie
join director on director.directorcode = movie.director
This is happening because in both cases the FK and PK columns refer to the same values.
In a SQL join operation, the result of the join will be the same regardless of the order of the FK and PK in the join condition, as long as the FK and PK columns refer to the same values.
The purpose of the join condition is to match up rows from the two tables based on the values in the FK and PK columns.
It does not matters what you write first in equals operation.
In my database I have two tables:
relationship table:
organization_id_first, organization_id_second, relationship_type
organization table:
primary key = org_id ; org_id, org_name, ...
How would I be able to join the organization table so that I could get the org_name for both organizations that have an entry in the relationship table? I don't think I can join on the same primary key. Would I have to do a subquery of some sort?
Thanks!
This is how i would do it in T-SQL ... just join it twice and make two different object
select or1.org_name, or2.org_name, rel.relationship_type from relationship rel
join organization or1 on rel.organization_id_first = or1.org_id
join organization or2 on rel.organization_id_second = or2.org_id
I have two tables Country and City. Both tables have only one column.
In country table I have values as
INDIA,UK,US and so on.
IN City table I have values like
LONDON,BANGALORE,DELHI,WASHINGTON and so on.
I want to write SQL query such that output should be like when I select UK ,LONDON should come in front of that ,when US ,WASHINGTON Should appear in US row and so on.
Please provide me the query.
You need to create a foreign key in the City table, then you join the tables together
ALTER TABLE city ADD COLUMN country VARCHAR(25);
ALTER TABLE city ADD PRIMARY KEY (city);
ALTER TABLE country ADD PRIMARY KEY (country);
ALTER TABLE city ADD FOREIGN KEY (country) REFERENCES country(country)
SELECT CONCAT(city, ", ", country) FROM city JOIN country USING (country)
It is impossible to make relation between these two tables since they have ONLY ONE column. You have to add [Country] column to the [City] table to known what country a city belongs to.
you need a third table to store the relationships between the two tables and you need to add ID fields to each of your existing tables.
table city
id | city
1 | chicago
table country
id | country
3 | United States
table lookup
id | city_id | country_id
5 | 1 | 3
you would have to perfom a JOIN to connect the tables
SELECT * FROMlookupJOIN city ON lookup.city_id = city.id JOIN country ON lookup.country_id = country.id
hope this helps
There are several options here.
The first thing to consider is whether you want to use the city/country name as the way of uniquely identifying a row. Although these are very unlikely to change, its not without precidence. Bombay => Mumbai, Ceylon => Sri Lnka, spelling mistakes, etc. Personally I'd recommend having an integer field as the PRIMARY KEY / UNIQUE IDENTIFIER on each table. You can then change the names (including spelling mistakes) without impacting anything else in the database.
You then need to relate the two tables. One option is to add a field to the CITY table that points to a unique identifier in the COUNTRY table. An alternative is to have a completely seperate table of two columns, relating each City's unique identifier to it's associated Country's unique identifier.
I have an SQL problem i was wondering if someone could help me out. Below is the schema of the database
Player
playerid (primary key)
playerName
PlaysAt
clubId (primary key)
playerId (fk to PLAYER.playerid)
yearsAtClub
My question is how do i select the clubId of the club where player named john and stephen play where john and stephen play at the same club. I have no idea how to get the club id in this case. i have managed to get the join part correct as im able to select the club id of john but cant get it when i specify the both players using WHERE playerName = john AND playerName = stephen.
Use:
SELECT c.clubid
FROM PLAYSAT c
JOIN PLAYER p ON p.playerid = c.playerid
WHERE p.playername IN ('john', 'stephen')
GROUP BY c.clubid
HAVING COUNT(DISTINCT p.playername) = 2
The key is that the number of parameters in the IN clause needs to match the COUNT in the HAVING clause -- in this case, two.
The DISTINCT helps in case there isn't a primary key or unique constraint on both the PLAYSAT.clubid and PLAYSAT.playerid columns -- two entries for "John" otherwise would be considered valid if for the same clubid value. Otherwise, the DISTINCT can be omitted from the query.
You can join twice to the same table by using the keyword as to create aliases:
select clubId
from PlaysAt
join Player as Player1 using (playerId)
join Player as Player2 using (playerId)
where Player1.playerName = 'john'
and Player2.playerName = 'stephen';
This assumes that the table Player has the primary key playerId (with a capital "I"). It doesn't in your code, but I couldn't tell if this was a typo. If you use the same name for primary key and foreign key you can take advantage of the using keyword, which makes queries much simpler.
So I have two tables in this simplified example: People and Houses. People can own multiple houses, so I have a People.Houses field which is a string with comma delimeters (eg: "House1, House2, House4"). Houses can have multiple people in them, so I have a Houses.People field, which works the same way ("Sam, Samantha, Daren").
I want to find all the rows in the People table corresponding to the the names of people in the given house, and vice versa for houses belong to people. But I can't figure out how to do that.
This is as close as I've come up with so far:
SELECT People.*
FROM Houses
LEFT JOIN People ON Houses.People Like CONCAT(CONCAT('%', People.Name), '%')
WHERE House.Name = 'SomeArbitraryHouseImInterestedIn'
But I get some false positives (eg: Sam and Samantha might both get grabbed when I just want Samantha. And likewise with House3, House34, and House343, when I want House343).
I thought I might try and write a SplitString function so I could split a string (using a list of delimiters) into a set, and do some subquery on that set, but MySQL functions can't have tables as return values.
Likewise you can't store arrays as fields, and from what I gather the comma-delimited elements in a long string seems to be the usual way to approach this problem.
I can think of some different ways to get what I want but I'm wondering if there isn't a nice solution.
Likewise you can't store arrays as fields, and from what I gather the comma-delimited elements in a long string seems to be the usual way to approach this problem.
I hope that's not true. Representing "arrays" in SQL databases shouldn't be in a comma-delimited format, but the problem can be correctly solved by using a junction table. Comma-separated fields should have no place in relational databases, and they actually violates the very first normal form.
You'd want your table schema to look something like this:
CREATE TABLE people (
id int NOT NULL,
name varchar(50),
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE houses (
id int NOT NULL,
name varchar(50),
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE people_houses (
house_id int,
person_id int,
PRIMARY KEY (house_id, person_id),
FOREIGN KEY (house_id) REFERENCES houses (id),
FOREIGN KEY (person_id) REFERENCES people (id)
) ENGINE=INNODB;
Then searching for people will be as easy as this:
SELECT p.*
FROM houses h
JOIN people_houses ph ON ph.house_id = h.id
JOIN people p ON p.id = ph.person_id
WHERE h.name = 'SomeArbitraryHouseImInterestedIn';
No more false positives, and they all lived happily ever after.
The nice solution is to redesign your schema so that you have the following tables:
People
------
PeopleID (PK)
...
PeopleHouses
------------
PeopleID (PK) (FK to People)
HouseID (PK) (FK to Houses)
Houses
------
HouseID (PK)
...
Short Term Solution
For your immediate problem, the FIND_IN_SET function is what you want to use for joining:
For People
SELECT p.*
FROM PEOPLE p
JOIN HOUSES h ON FIND_IN_SET(p.name, h.people)
WHERE h.name = ?
For Houses
SELECT h.*
FROM HOUSES h
JOIN PEOPLE p ON FIND_IN_SET(h.name, p.houses)
WHERE p.name = ?
Long Term Solution
Is to properly model this by adding a table to link houses to people, because you're likely storing redundant relationships in both tables:
CREATE TABLE people_houses (
house_id int,
person_id int,
PRIMARY KEY (house_id, person_id),
FOREIGN KEY (house_id) REFERENCES houses (id),
FOREIGN KEY (person_id) REFERENCES people (id)
)
The problem is that you have to use another schema, like the one proposed by #RedFilter. You can see it as:
People table:
PeopleID
otherFields
Houses table:
HouseID
otherFields
Ownership table:
PeopleID
HouseID
otherFields
Hope that helps,
Hi you just change the table name places, left side is People and then right side is Houses:
SELECT People.*
FROM People
LEFT JOIN Houses ON Houses.People Like CONCAT(CONCAT('%', People.Name), '%')
WHERE House.Name = 'SomeArbitraryHouseImInterestedIn'