I am trying to fetch data from the 2 tables using joins. But I don't know how to do it. I have read about joins but it wasn't making any sense since I am new.
I have two tables.
Playgrounds Inspection
id u_id id playground_id
1 2 1 1
2 2 2 2
In playgrounds table id is the playground id and is unique and u_id is the user of the playground.
In inspection table id is unique and playground_id is used as a foreign key from playgrounds table's id.
My problem is that I have to pass id and u_id to the the query in playgrounds table then it should select id from playground table. Then it should select every thing from inspection table based on that id .
Hope I have explained it properly.
Any help is much appreciated.
Thanks in advance
JOIN operations, whether INNER JOIN, LEFT JOIN, or RIGHT JOIN, have this overall syntax.
table_expression JOIN table_expression ON boolean_expression
When the Boolean expression is true, the JOIN concatenates the matching rows of the two tables into a single row in the result.
In your case, you want the ON clause's Boolean expression to say
Playgrounds.id = Inspection.playground_id
because that's how you know a row from Inspection relates to a row in Playgrounds. Accordingly, a statement like
SELECT Inspection.id AS Inspection_ID,
Playgrounds.id AS Playground_ID,
Playgrounds.u_id AS User_ID
FROM Playgrounds
JOIN Inspection ON Playgrounds.id = Inspection.playground_id
WHERE Playgrounds.u_id = something
AND Playgrounds.id = something_else
See how it goes? Your SELECT makes a new table, sometimes called a result set, by JOINing the rows of two existing tables on the criteria you choose in the ON clause.
You can put anything you want into the ON clause. You could put
Playgrounds.id = Inspection.playground_id OR Inspection.id < 20
or
Playgrounds.id = Inspection.playground_id OR Inspection.scope = 'citywide'
for example (if you had a scope column in the Inspection table).
But, don't go there until you master the basic JOIN operation.
Related
I just can't see the problem with how I'm making my foreign keys and I'm just really confused why I keep getting the wrong result. Here are screenshots from my workbench
Here are my tables:
And here's my diagram
I've also tried to normalize my tables and I was kinda expecting my query to return a similar result like in the sample table (Questions table) where it will only show 2 results since I want to query where idsurvey = 1 I made in this image:
My question is that, how do I fix my foreign key so that if I want to query
select * from survey.survey, survey.questions where idsurvey = 1
it will only return 2 rows? (based on sample data in the workbench screenshot)
Any comments and suggestions on my diagram would also be greatly appreciated.
When you have two tables in the from clause, every row from the first table is matched with every table from the second table. This is known as a Cartesian Product. Usually, this isn't the behavior you'd want (like it isn't in this case), and you'd use a condition to tell the database how to match these two tables:
SELECT *
FROM survey.survey s, survey.questions q
WHERE s.idsurvey = q.survey_id AND idsurvey = 1
While this should work, it's quite outdated to use multiple tables in the same from clause. You should probably use an explicit join clause instead:
SELECT *
FROM survey.survey s
JOIN survey.questions q ON s.idsurvey = q.survey_id
WHERE idsurvey = 1
I would like to list in table (staging) the number of related records from table (studies).
So far this statement works well but returns only the rows where there are >0 related records:
SELECT staging.*,
COUNT(studies.PMID) AS refcount
FROM studies
LEFT JOIN staging
ON studies.rs_number = staging.rs
GROUP BY staging.idstaging;
How can I adjust this statement to list ALL rows in table (staging) including where there are zero or null related records from table (studies)?
Thank you
You have the tables in the wrong order in the LEFT JOIN:
SELECT staging.*, COUNT(studies.PMID) AS refcount
FROM staging LEFT JOIN
studies
ON studies.rs_number = staging.rs
GROUP BY staging.idstaging;
LEFT JOIN keeps everything in the first ("left") table and all matching rows in the second. If you want to keep everything in the staging table, then put it first.
And, in case anyone wants to complain about the use of staging.* with GROUP BY. This particular usage is (presumably) ANSI compliant because staging.idstaging is (presumably) a unique id in that table.
query:
select DOG_CD,ANIMAL_CD
from FKAGM
where FKAG = 12024
Displays 3 rows
DOG_CD - ANIMAL_CD are column names and below each column is 3 numerical values yielded from the above query & I have no clue how to draw a table on here to depict that. =(
There is a table called Dog_Animal that has a column called "Name" (Dog_Animal.Name) that I want to join with this above query. I want to join on ANIMAL_CD as FKAGM table and the DOG_ANIMAL table have the ANIMAL_CD column in common. I'd like to display "Name" right next to the ANIMAL_CD column. The issue is when I join the tables it displays like every instance of DOG_CD and ANIMAL_CD within the Dog_Animal table (Which is thousands) something similar to the below illustration. since the Dog_Animal table has thousands of DOG_CD and ANIMAL_CODE fields populated. I just want it to be limited to the three rows that are returned by the above query (Limit or distinct or something) and input the Dog_Animal.Name next to Animal_CD. I've been working on this for an hour and I know it must be so simple, but I can't seem to get it to work. I am not sure if a subquery is needed or exists, or case, or what. If you can figure this out I would be so thankful!
DOG_CD - ANIMAL_CD - Dog_Animal.Name with the same 3 rows of data just now a name included
select
f.DOG_CD,f.ANIMAL_CD,d.name
from FKAGM f
inner join dog_animal d
on d.animal_cd = f.animal_cd
where f.FKAG = 12024;
inner join would work for you. If you only need to limit it to 3 results, add limit 3 order by f.dog_cd at the end of your query.
Question - let's say I have 2 tables.
Table 1 - name is permission_list, columns are ID (unique ID), col_ID, user_ID
Table 2 - name is list_entries, Columns are ID (unique ID), title, description, status
I want to select all the rows from table 2 that have status of 'public' as well as all the rows from table 2 that the ID from table 2 shows up in table 1 (under the column col_ID) AND if the user_ID in table 1 matches a certain value. So, anything public, or anything that this specific user has listed under the permissions table. This query would also remove duplicates - in case the user gets a public entry listed in their permissions_list, it wouldn't show up twice.
Hope that makes sense!
Here you go:
SELECT DISTINCT table2.* from table2
LEFT JOIN table1 USING (id)
WHERE status='public'
OR user_ID='someuser';
You need to get some education on JOIN for your first thing, and the second thing is called DISTINCT.
Start here... https://www.google.com/
You have not specified your join condition so we can't give you code samples really. Also the way you worded your question, I'm not entirely sure you don't want a UNION. Read up on those concepts and come back here when you can improve the question.
SELECT table_2.status, table_2.ID, table_1.col_ID
FROM table_1 JOIN table_2
WHERE table_2.status = 'public'
AND table_2.ID = table_1.col_ID
AND table_1.user_ID = 'certain value'
;
Try this
Why I am getting so many records for this
SELECT e.OneColumn, fb.OtherColumn
FROM dbo.TABLEA FB
INNER JOIN dbo.TABLEB eo ON Fb.Primary = eo.foregin
INNER JOIN dbo.TABLEC e ON eo.Primary =e.Foreign
WHERE FB.SomeOtherColumn = 0
When I am running this I am getting Millions of records which is not the correct case, all tables has less number of records.
I need to get the columns from TableA and TableC and because they are not joined logically so I have to use TableB to act as bridge
EDIT
Below is the count:
TABLEA = 273551
TABLEB = 384412
TABKEC = 13046
Above Query = After 2 minutes I have forcefully canceled the query.. till that time the count was 11437613
Any suggestion?
To figure out what is going on in such a query where the results are not as expected, I tend to do this. First I change to a SELECT * (Note this is only for figuring out the problem, do not use SELECT * on production, ever!) Then I add an order by for the ID frield from tableA if there is not one in the query.
So now I run the query up to the first table including any where conditions that are from the first table. I comment out the rest. I note the number of records returned.
Now I add in the second table and any where conditions from it. If I am expecting a one to relationship, and if this query doesn't return the smae number of records, then I look at the data that is being returned to see if I can figure out why. Since the contents are ordered by the table1 ID, you can ususally see examples of some records that are duplicated fairly easily and then scroll over until you find the field that causes the differnce. Often this means that you need some sort of addtional where clause or aggregation on the fields in the next table to limit to only one record. JUSt note down the problem at this point though as you may be able tomake the change more effectively in the next join.
So add inteh the third table and again, not the number of records and then look closely at the data where the id from A is repeated. LOok at the columns you intend to return, are they always teh same for an id? If they are differnt then you do not havea one-one relationship and you need to understand that either theri is a data integrity problem or you are mistaken in thinking there is a one-to-one. If tehy are the same, then a derived table may be in order. You only need the ids from tableb so the join could look something like this:
JOIN (SELECT MIn(Primary), foreign FROM TABLEB GROUP BY foreign) EO ON Fb.Primary = eo.foreign
Hope this helps.