简体   繁体   中英

Select multiple records from inner joined table by id

Trying to inner join for the first time and thing are going well, only the last step is missing to receive correct data from my database. This is my SQL query:

SELECT roadtrip_tblgeneral.*, roadtrip_tblhotels.hotel, roadtrip_tbllocation.location, roadtrip_tbltransport.transport
FROM roadtrip_tblgeneral
INNER JOIN roadtrip_tblhotels
ON roadtrip_tblgeneral.id = roadtrip_tblhotels.tripid
INNER JOIN roadtrip_tbllocation
ON roadtrip_tblgeneral.id = roadtrip_tbllocation.tripid
INNER JOIN roadtrip_tbltransport
ON roadtrip_tbltransport.id = roadtrip_tbltransport.tripid
WHERE roadtrip_tblgeneral.tripcode = 'cb8v73x9'

This is the response I get from the database: all looks fine, but one user can add multiple vehicles into transport with the same id and I want to get all those back and not just one. (eg. Metro, Car, Bike, ...)

id  tripname      tripcode  hotel   location    transport        
1   London        cb8v73x9  Seaside London      Metro

I think this might be your issue

ON roadtrip_tbltransport.id = roadtrip_tbltransport.tripid

You appear to be trying to join two tables based on a condition independent of the first table being joined

Looking at the pattern of your previous lines did you mean this:

ON roadtrip_tblgeneral.id = roadtrip_tbltransport.tripid

As @kickstart said, you can move all of the transport modes into one column by changing your SELECT Statement to

SELECT roadtrip_tblgeneral.*, roadtrip_tblhotels.hotel, roadtrip_tbllocation.location, GROUP_CONCAT(roadtrip_tbltransport.transport)

It may well be better to handle this at application level if you need to access each transport type individually, but GROUP_CONCAT() should be fine if all you want is a string a comma separated transport modes as an individual item

Use GROUP BY and GROUP_CONCAT to get all the transports used in one field, with the values comma separated

SELECT roadtrip_tblgeneral.*, roadtrip_tblhotels.hotel, roadtrip_tbllocation.location, GROUP_CONCAT(roadtrip_tbltransport.transport)
FROM roadtrip_tblgeneral
INNER JOIN roadtrip_tblhotels
ON roadtrip_tblgeneral.id = roadtrip_tblhotels.tripid
INNER JOIN roadtrip_tbllocation
ON roadtrip_tblgeneral.id = roadtrip_tbllocation.tripid
INNER JOIN roadtrip_tbltransport
ON roadtrip_tblgeneral.id = roadtrip_tbltransport.tripid
WHERE roadtrip_tblgeneral.tripcode = 'cb8v73x9'
GROUP BY roadtrip_tblgeneral.id

Note you should really use all the non aggregate fields in the GROUP BY clause, but the above should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM