3表连接一个表中的一个字段和另一个表中的一个字段

时间:2011-01-31 19:13:19

标签: sql mysql join

我有这个查询

SELECT cities.city, city_time.time_slot 
FROM cities, city_date, city_time 
WHERE city_time.city_date_id = city_date.city_id = city_date.city_id =  cities.id 
AND city_time.city_date_id = '1'

我正在尝试将cities.city和city_time.time_slot放入同一行,它们通过city_date连接,

cities has- 
===========
id
city, 

city_date  has
===========
id
city_id (fk for city_table)

city_time has
==============
city_date_id (FK for city_date table)
time_slot

尝试了几种方法 -

SELECT cities.city, city_time.time_slot 
FROM (city_date LEFT JOIN cities ON city_time.city_date_id = city_date.city_id ) 
LEFT JOIN city_date ON city_time.city_date_id = city_date.city_id 
WHERE  city_time.city_date_id = '1'

我只想要来自cities表的city字段链接到city_time表中的time_slot字段。甚至不需要左连接,但我想我会包括它来帮助你理解我的想法。

3 个答案:

答案 0 :(得分:1)

select c.city, ct.time_slot
    from cities c
        inner join city_date cd
            on c.id = cd.city_id
        inner join city_time ct
            on cd.id = ct.city_date_id
    where ct.city_date_id = 1

答案 1 :(得分:0)

从你的其他问题来看,这看起来就是你所追求的 请开始使用较短的名称(希望仍然有意义)用于别名。

SELECT c.city, t.time_slot 
FROM cities c
LEFT JOIN city_date d on d.city_id = c.id 
LEFT JOIN city_time t on t.city_date_id = d.city_id AND t.city_date_id = '1'

答案 2 :(得分:0)

这两个表中应该有一些共同点,以便您可以比较它并拥有您想要打印的内容..例如添加类似城市ID和城市时间ID的内容具有相同的记录。