简体   繁体   English

MYSQL:连接两个表并使用一个随机列

[英]MYSQL: joining two tables and using random column from one

I'm rather new to mySql and I can't seem to get my head around a problem I have. 我对mySql很新,我似乎无法解决我遇到的问题。 What I want to do is to use a table (LessonPlans) and join it with a random image from another table (Images), but only if that image is marked with the same language as the LessonPlans. 我想要做的是使用一个表(LessonPlans)并将其与另一个表(图像)中的随机图像连接,但前提是该图像使用与LessonPlans相同的语言标记。 The images should continue adding only as long as there are more input from LessonPlans. 只要LessonPlans有更多输入,图像就应该继续添加。

In detail: 详细:

I need to show Name , Level and Aim from LessonPlans together with a random image ( Name-img ) from Images , but only when both LessonPlans and Images have Language (for example English) in common. 我需要一个随机图像( 名称-IMG)图像一起显示名称 ,从LessonPlans 水平目标 ,但只有当LessonPlans图像有共同的语言 (例如英语)。 This should be continued as long as there are rows in LessonPlans , even if that means repeating Images . 只要LessonPlans中有行,即使这意味着重复图像 ,也应该继续这样做。

I have tried all sorts of solutions from differnet sources, but I either get everything random, or everything repeated. 我尝试过各种来自不同来源的解决方案,但我要么随便得到所有东西,要么重复一切。

ps. PS。 I'm new to Stackoverflow so excuse me if I didn't make myself very clear 我是Stackoverflow的新手,请原谅我,如果我不清楚自己

//Edit //编辑

This is the tables: 这是表格:

LessonPlans Id Subject Language Level Aim

Images Id Name-img Language

/Håkan /哈坎

SELECT LessonPlans.Name , LessonPlans.Level , LessonPlans.Aim , LessonPlans.language ,
       Images.img, Images.language 
FROM   LessonPlans , Images
ON  LessonPlans.commonfield=Images.commonfield
WHERE   LessonPlans.language      = 'English';

Try this -->> 试试这个 - >>

SELECT LessonPlans.Subject , LessonPlans.Level , LessonPlans.Aim , LessonPlans.language ,
       Images.Name_img
FROM   LessonPlans INNER JOIN Images
ON  LessonPlans.language=Images.language
SELECT * FROM
    (SELECT l.Id, l.Subject, l.Language, i.`Name-img` 
        FROM LessonPlans l, Images i
        WHERE l.Language = i.Language
        ORDER BY RAND()
    ) a
GROUP BY a.Subject
ORDER BY a.Id

You can use all fields you need. 您可以使用所需的所有字段。 Please check this example at the SQLFiddle . 请在SQLFiddle上查看此示例。 Sometimes image names may repeat because there are few images in the sample schema. 有时图像名称可能会重复,因为示例模式中的图像很少。

UPD 1: Add specific language UPD 1:添加特定语言

SELECT * FROM
    (SELECT l.Id, l.Subject, l.Language, i.`Name-img` 
        FROM LessonPlans l
        JOIN Images i
        ON l.Language = i.Language
        WHERE l.Language = 'en'
        ORDER BY RAND()
    ) a
GROUP BY a.Subject
ORDER BY a.Id

Try this at the SQLFiddle SQLFiddle上试试这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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