使用多行连接2个表

时间:2016-06-05 12:03:02

标签: sql-server join group-by

我有两张桌子。

Main 
Id Name
1  abc
2  efg

Image
MainId ImagePath
1        ..//
1        ..//
2        ..//
1        ..//
2        ..//

我需要将这两个表组合在一起,以MainId为键。它可以链接Image图像中的任何随机图像。

但是目前我正在加入时,它会加入并显示Image表中的所有行。

SELECT a.Id,b.ImagePath FROM Main a, Image b  WHERE a.Id=b.MainId  

2 个答案:

答案 0 :(得分:3)

选择随机图像的另一种方法是......

Select m.ID , I.ImagePath
FROM Main m 
 CROSS APPLY (SELECT TOP 1 ImagePath
              FROM Image
              WHERE MainId = m.ID
              ORDER BY NEWID()
              ) I(ImagePath)

答案 1 :(得分:1)

您可以使用相关查询:

SELECT t.id,
       (SELECT s.ImagePath FROM Image s
        WHERE t.id = s.MainId
        LIMIT 1) as imagePath
FROM Main t

或者只是加入一个包含imagePath ID SELECT t.id,s.ImagePath FROM Main t INNER JOIN(SELECT s.MainId,max(s.ImagePath) as max_im FROM Image s GROUP BY s.MainId) tt ON(t.id = tt.max_un) 的派生表:

def init_localization():
# Searches config file, if created.
config_name = 'default'
configpath = find_config(config_name)
try:
    config_module = Config(configpath)
    if config_module.core.not_configured:
        lang = raw_input("Language code: ")
    else:
        if config_module.has_option('core', 'lang'):
            lang = config_module.lang
        else:
            lang = raw_input("Language code: ")
except ConfigurationError:
    lang = raw_input("Language code: ")

filename = ("translations/messages_%s.mo" % lang)

try:
    logging.debug("Opening message file %s for locale %s", filename, lang)
    trans = gettext.GNUTranslations(open( filename, "rb" ) )
except IOError:
    logging.debug( "Locale not found. Using default messages" )
    trans = gettext.NullTranslations()

trans.install()