简体   繁体   中英

Return all columns from table 1, and one column from table 2

I'm trying to do an SQL query that will return all values in table 1 if it has a corresponding value in table 2. I also want to return that corresponding value in table 2, but only limit it to one if their are multiple values.

Here is an example of the data:

TABLE 1: album
-------------
ALBUM_ID
1      
4         
5
13

TABLE 2: photo
-------------
PHOTO_ID       ALBUM_ID          IMAGE
1              4                 img1
4              4                 img2
6              1                 img17
15             4                 img15
24             3                 img3

So with the above data, I want the following returned:

ALBUM_ID: 1 IMAGE17 // because album 1 has an associated image ALBUM_ID: 4 IMAGE1 // because album 4 has an associated image, but I only want one image

My current query is:

SELECT * 
FROM album
INNER JOIN photo ON album.album_id=photo.album_id 
GROUP BY album.album_id

However this is returning all the columns in photo, I just want it return Image, and not photo_id or album_id

Any help would be great, thanks!

try this:

SELECT al.*, ph.column_name
FROM album AS al
INNER JOIN photo AS ph ON album.album_id=photo.album_id 
GROUP BY album.album_id

sorry but i dont know what sql server you are using ...

pls/sql and t-sql have special function for this duplicit results

mysql have not i think ...

but try it with subquery with limit

for mysql try next query // not tested .. write from my broken mind

SELECT 
   alb.*, -- or all columns with prefix alb
   pho.IMAGE
FROM album alb
INNER JOIN (
              SELECT ALBUM_ID, IMAGE FROM photo LIMIT = 1
) pho ON pho.ALBUM_ID = alb.ALBUM_ID

working ?

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