MySQL Join query: Two main and one linking table

LordVader :

I have a Star Wars project that I am working on for Uni.

In my database, I have multiple tables and linking tables. I'm trying to query

"What mode of transport has been used by Rey, Obi-Wan Kenobi and C-3PO?"

Answer (obviously) is Millennium Falcon.

I've set up the query using INNER JOINs but I'm stuck at the end.

SELECT t.type AS OnlyTransportItCouldBe 
FROM transport AS t
INNER JOIN person_transport AS pt
ON pt.transport_id = t.id
INNER JOIN person AS p
ON pt.person_id = p.id
WHERE p.name = 'Rey'

The above returns 3 ships, but I'm confuddled as to how also check Old Ben and Goldenrod. I've tried AND p.name = "Obi-Wan Kenobi" and it returns blank. If I try WHERE p.name = 'Rey', 'Obi-Wan Kenobi' it fails, if I try WHERE p.name = 'Rey' AND 'Obi-Wan Kenobi', the result is blank. I know it's something really simple, but I can't seem to find a solution.

forpas :

If your requirement is to get the common modes of transport that have been used by Rey, Obi-Wan Kenobi and C-3PO then you must group by type and add a having clause like ethis:

SELECT t.type AS OnlyTransportItCouldBe 
FROM transport AS t
INNER JOIN person_transport AS pt ON pt.transport_id = t.id
INNER JOIN person AS p ON pt.person_id = p.id
WHERE p.name IN ('Rey', 'Obi-Wan Kenobi', 'C-3PO')
GROUP BY t.type
HAVING COUNT(DISTINCT p.name) = 3

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=276805&siteId=1