两个表之间的简单连接

时间:2014-01-08 06:21:21

标签: mysql join

我需要一些基本的MySQL语句帮助。

下面有两张桌子:餐和人。

TABLE meals
================================
=== id === name === meal     ===
================================
--- 1  --- John --- Pizza    ---
--------------------------------
--- 2  --- Jill --- Pasta    ---
--------------------------------
--- 3  --- Jill --- Pizza    ---
--------------------------------
--- 4  --- John --- Sandwich ---
--------------------------------
--- 5  --- Jill --- Rice     ---
--------------------------------

TABLE people
=========================================
=== name  === email           === age ===
=========================================
--- John  --- john@test.com   --- 24  ---
-----------------------------------------
--- Jill  --- jill@test.com   --- 24  ---
-----------------------------------------
--- Alice --- alice@test.com  --- 32  ---
-----------------------------------------

我要做的是从表names中获取meals的不同列表,然后仅使用输出排序顺序从people表中获取这些行是age然后是email(所以如果年龄相同,它会通过电子邮件进行二次排序)。

我很困惑!

3 个答案:

答案 0 :(得分:0)

试试这个:

SELECT DISTINCT(name.meals),email.people,age.people from meals,people 
where name.meals=name.people ORDER BY AGE;

希望这能帮到你!

答案 1 :(得分:0)

由于1 to npeople表之间存在简单的meals关系,因此我认为您不必执行distinct然后group by 1}}。你所要做的就是:

  SELECT p.name 
    FROM people p
   WHERE EXISTS (SELECT 1
                   FROM meals m
                  WHERE m.name = p.name)
ORDER BY p.age, p.email

答案 2 :(得分:0)

尝试,

Select DISTINCT(m.Name), p.email,p.age from meals as m,people as p where m.name = p.name