Question about combining data from two tables with many to many relationship - database

Could anyone please explain (or link to a good tutorial) on how to combine data from two tables which is connected with a 'link-table'?
One table contains question
One table contains categories
One table contains question_categories
Each question belongs to many categories, and each category can have many questions.
The link table contain two id's, categoryID and questionID(they are primary keys in the table) with a foreign key to category and question table.
But I do not completely understand how I can write an SQL select that for instance displays what kind of categories question with ID 2 belongs to.
And thorough explanation would be MUCH appreciated!
Thanks in advance.

You use the JOIN clause to connect the tables.
SELECT Q.*
FROM question Q
INNER JOIN question_categories QC
ON q.questionId = QC.questionID
WHERE QC.categoryID = 2
To break it down:
SELECT Q.* -- Get all fields from the alias Q (though you should specify fields)
FROM question Q -- From the question table, aliased Q
INNER JOIN question_categories QC -- Join on the question_categories table (QC)
ON q.questionId = QC.questionID -- Using the questionIds on both tables as join criteria
WHERE QC.categoryID = 2 -- constrain to only categoryId of 2
Edit (example for categories by questionId) as requested in comments:
SELECT C.*
FROM category C
INNER JOIN question_categories QC
ON C.categoryId = QC.categoryID
WHERE QC.questionID = 1

Related

How do I query three related tables?

I'm new to databases and I'm having a hard time figuring this out. Any assistance would be greatly appreciated
Deliveries Table
-- ID (PK)
-- DriverID (FK to Drivers Table)
Drivers Table
-- ID (PK)
-- LocationID (FK to Locations Table)
Locations Table
-- ID (PK)
-- RestaurantID (FK to Restaurants Table)
Restaurant Table
--ID (PK)
A Restaurant can have multiple locations (1 to many). A location can have multiple drivers (1 to many). a Driver can have multiple deliveries (1 to many). This design is supposed to break things out in 3rd normal form. So if I want to go to the deliveries table and get all of the deliveries associated with a particular restaurant, how would I query or do a join for that? Would I have to add a second foreign key to Deliveries that directly references the Restaurant table? I think after I see the query I can figure out what is going on. Thx
You can use left or right outer join to make a combined table and then you can easily query it, or else you can use a query with multiple sub-queries inside it to attain the required result without using join. Here is an example on how to use sub-query for your use-case.
SELECT ID FROM Deliveries De
WHERE De."DriverID" IN (SELECT ID FROM Drivers Dr
WHERE Dr. "LocationID" IN (SELECT ID FROM Locations L
WHERE L. "RestaurantID" IN (SELECT ID FROM Restaurant)))
I hope this solves your issue without using join statement.
You can use inner join or union depending on what you want to achieve. Example:
SELECT a."articleId" AS id, a.title, a."articleImage" AS "articleImage/url", c.category AS "category/public_id", a."createdOn", concat("firstName", ' ', "lastName") AS author
FROM articles a
INNER JOIN users u ON a."userId" = u."userId"
INNER JOIN categories c ON a."categoryId" = c."categoryId"
UNION
SELECT g."gifId" AS id, g.title, g."imageUrl" AS "articleImage/url", g.public_id AS "category/public_id", g."createdOn", concat("firstName", ' ', "lastName") AS author
FROM gifs g
INNER JOIN users u ON g."userId" = u."userId"
ORDER BY "createdOn" DESC
You can say how you want to get the results for more detailed query.
If I understand what you want to do then it maybe like this,
1st you have to join all those table to get corresponding result you want,
the join condition will be
select <your desire column name>
from Restaurant A,Locations B,Drivers C,Deliveries D
where A.ID = B.RestaurantID
and B.ID = C.LocationID
and C.ID = D.DriverID
Hope this is helpful, fell free to say anything.

Basic SQL - What’s best possible answer if you know ?

In SQL Server, you have a Customer table and an Order table. The relationship between the two tables is the CustomerId field. It’s a foreign key from the Orders back to the primary table Customer. With that in mind, how would you write a query that would retrieve Customers that don’t have Orders.
The following will return all customers on the left of the query and will show a NULL on the right where there are no matching order records.
We then filter to only show those with NULL in the right table.
SELECT *
FROM Customers c
LEFT JOIN Orders o
ON c.CustomerId = o.CustomerId
WHERE o.CustomerId IS NULL
Below is a great diagram explaining the different types of join

I want to select from two tables (a,b) which are related to each other through third table(c), but table a has a composite primary key

I want to select from two tables (customers,machins) which are related to each other through third table(orders), but table a has a composite primary key
Table customers has primary key as
id
Table machins has a composite primary key with these two columns:
machinId
machineModel
And these two are related to table orders
Id(fk)
machine(fk)
machintype
I want to select from customers and machins all machines that a person has bought (orders)
My select command is
Select c.name, c.land, m.namemachin
from orders o
inner join customers c on c.id = o.id
inner join machins m on o.machine = m.Id
where c.name = 'karl' and m.machine = o.machintype
But it doesn't work
Can you please help me?
If you have a composite primary key in table machins then both of that column should be available in table orders for a proper relation. Then only you can do a proper join this tables for a select query.
As per the discussion m.machineModel = o.machintype
So please try this query
Select c.name, c.land, m.namemachin
from orders o
inner join customers c on c.id = o.id
inner join machins m on m.machinId = o.machine
and m.machineModel = o.machintype
where c.name = 'karl'
If your fetching is something related to string concatenation i.e to obtain all machines as string. I think you can use STUFF and FOR XML PATH.
Or else go through th below link it might help
http://www.w3resource.com/sql/joins/using-a-where-cluase-to-join-two-tables-related-by-a-composite-primary-key-or-foriegn-key-pair.php

SQL Server Many to many on the same table how to join and query

I have the following relationship between 2 table.
There is a many to many relationship between 2 tables.(2 foreign keys in BigGroups pointing to GroupId in Table Groups)
SELECT GroupName FROM Groups where GroupId IN
(SELECT bg.AssociatedGroupId
FROM BigGroups bg INNER JOIN Groups g ON bg.GroupId=g.GroupId
WHERE bg.GroupId=#GroupId)
This query returns me what I am looking for but I believe there could be a better way of doing this(better performance). Or maybe I should change the relationship?
If I've read it right then you're looking for the GroupName of AssociatedGroups for the #GroupId parameter? This is a more concise query to achieve the same thing.
SELECT g.GroupName
FROM BigGroups bg
INNER JOIN Groups g ON g.GroupId = bg.AssociatedGroupId
WHERE bg.GroupId = #GroupId
Nothing wrong with that relationship, although I think it's 1-to-many; 1 group can have zero or more associated groups.

Help with Many-to-Many Filtering Queries

I'm trying to figure out how to efficient implement tags in my database.
One approach is to have a table of articles (let's say Articles, ArtID int PK, ArtText varchar(max)), and a table of tags (let's say Tags, TagID int PK, TagTitle varchar(15)). And then I'll create a join table to create a many-to-many relationship between Articles and Tags (let's say ArticleTags, ArtID int, TagID int (compound primary key).
My first question is what is the best way to write a query to find all the articles associated with a given tag? I know about joins if I want to return the combined data, but what is the most efficient query if I just want to know which article rows are associated with a particular tag. In real life, I will need to find articles with multiple tags and it would be nice to also find articles that are NOT associated with a particular tag.
My second question is about whether or not my Tags table should have an int PK? Does it make more sense to use the TagTitle as the primary key?
(1)
(a) Articles with a particular tag:
SELECT columns FROM Articles WHERE EXISTS
(SELECT null FROM ArticleTags at
WHERE at.ArtID = Articles.ArtID AND at.TagID=x)
(b) Articles without a particular tag:
SELECT columns FROM Articles WHERE NOT EXISTS
(SELECT null FROM ArticleTags at
WHERE at.ArtID = Articles.ArtID AND at.TagID=x)
(2) Using TagTitle is faster if you're just getting the list of tags associated with an article, but for most other possible operations, a surrogate int will be faster.
1a) My first question is what is the best way to write a query to find all the articles associated with a given tag?
select ArtID -- if only IDs are required
from ArticleTags
where TagID=1 -- or use the text (where tagtitle='x')
select A.*
from ArticleTags T inner join Articles A on A.ArtID = T.ArtID
where T.TagID=1
1b) In real life, I will need to find articles with multiple tags
-- has tags 1,3 and 8
select T1.ArtID
from ArticleTags T1
inner join ArticleTags T2 on T1.ArtID = T2.ArtID and T2.TagID = 3
inner join ArticleTags T3 on T1.ArtID = T3.ArtID and T3.TagID = 8
where T1.TagID=1
-- or use the text (tagtitle='x') on each filter
In some cases, this form works faster. This or the preceeding one can be joined to get the article records.
select ArtID
from (
select T1.ArtID from ArticleTags T1 where T1.TagID=1
union all
select T2.ArtID from ArticleTags T2 where T2.TagID=3
union all
select T3.ArtID from ArticleTags T3 where T3.TagID=8
) X
group by ArtID
having count(ArtID) = 3
1c) and it would be nice to also find articles that are NOT associated with a particular tag.
select A.*
from Articles A
left join ArticleTags T on T.ArtID = A.ArtID and T.TagTitle = 'nomatch'
where T.ArtID is null
2) My second question is about whether or not my Tags table should have an int PK? Does it make more sense to use the TagTitle as the primary key?
I am firmly in the camp that says each table should have a sequential, meaningless integer ID. It reduces space of storage (FK from other tables) and int lookup / range merging is always faster than varchar.

Resources