[英]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. 我正在尝试执行一个SQL查询,如果表2中有对应的值,它将返回表1中的所有值。我也想返回表2中的对应值,但是如果它们是多个值,则仅将其限制为一个。
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 ALBUM_ID:1 IMAGE17 //因为相册1具有关联的图像ALBUM_ID:4 IMAGE1 //因为相册4具有关联的图像,但是我只想要一个图像
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 但是,这将返回photo中的所有列,我只希望它返回Image,而不是photo_id或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 ... 对不起,但我不知道您正在使用什么SQL Server。
pls/sql and t-sql have special function for this duplicit results pls / sql和t-sql对这种重复结果具有特殊功能
mysql have not i think ... MySQL没有我认为...
but try it with subquery with limit 但是尝试使用带有限制的子查询
for mysql try next query // not tested .. write from my broken mind 对于mysql,请尝试下一个查询///未经测试..
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 ? 工作?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.