这个SQL有什么问题?

时间:2010-07-19 09:42:00

标签: sql sql-server asp-classic left-join

我确信这是一个非常简单的东西,我忽略了,但MS SQL对我来说是新的 - 我(或者至少我认为)对基本的MySql相当熟悉。

SELECT l.link_id, l.link_allcount, d.desc_id, d.desc_count, d.desc_text, h.hour_17,   dl.day_19 
FROM lnktrk_links AS l, lnktrk_hourly AS h, lnktrk_daily AS dl 
LEFT JOIN lnktrk_descriptions AS d ON l.link_id = d.link_id 
WHERE l.link_id = h.link_id AND l.link_id = dl.link_id AND l.link_is_click = 1

我得到的错误是:

'The multi-part identifier "l.link_id" could not be bound.

然而l.link_id肯定存在。没有连接的以下查询按预期工作:

SELECT l.link_id, l.link_allcount, d.desc_id, d.desc_count, d.desc_text, h.hour_17, dl.day_19 
FROM lnktrk_links AS l, lnktrk_hourly AS h, lnktrk_daily AS dl, lnktrk_descriptions AS d 
WHERE l.link_id = h.link_id AND l.link_id = dl.link_id AND d.link_id = l.link_id AND l.link_is_click = 1

4 个答案:

答案 0 :(得分:2)

试试这个:

SELECT 
l.link_id, 
l.link_allcount, 
d.desc_id, 
d.desc_count, 
d.desc_text, 
h.hour_17,   
dl.day_19 

FROM lnktrk_links AS l
inner join lnktrk_hourly AS h
on l.link_id = h.link_id
inner join  lnktrk_daily AS dl
on l.link_id = dl.link_id 
LEFT JOIN lnktrk_descriptions AS d ON l.link_id = d.link_id 
WHERE   l.link_is_click = 1

答案 1 :(得分:1)

LEFT JOIN加入lnktrk_daily AS dllnktrk_descriptions AS d - 这些都不会被称为l,因此JOIN s { {1}}子句ON并不意味着什么。

现在看起来你正在使用'cross join plus l子句'而不是'内部联接与WHERE子句'样式。如果切换到后者,那么ON应该在整个l子句中具有意义。

答案 2 :(得分:1)

我认为语法绑定

lnktrk_daily AS dl 
LEFT JOIN lnktrk_descriptions AS d 
    ON l.link_id = d.link_id 

比逗号分隔的子句更紧密,所以你在那部分没有l

您拥有的内容分组为:

SELECT l.link_id, l.link_allcount, d.desc_id, d.desc_count, d.desc_text, h.hour_17,   dl.day_19 
FROM lnktrk_links AS l, lnktrk_hourly AS h, 
( lnktrk_daily AS dl 
  LEFT JOIN lnktrk_descriptions AS d 
  ON l.link_id = d.link_id )
WHERE l.link_id = h.link_id AND l.link_id = dl.link_id AND l.link_is_click = 1

答案 3 :(得分:1)

你应该加入所有 - 而不是使用FROM

试试这个

SELECT l.link_id, l.link_allcount, d.desc_id, d.desc_count, d.desc_text, h.hour_17,   dl.day_19 
FROM lnktrk_links AS l
LEFT JOIN lnktrk_hourly AS h ON l.link_id = h.link_id
LEFT JOIN lnktrk_daily AS dl ON l.link_id = dl.link_id
LEFT JOIN lnktrk_descriptions AS d ON l.link_id = d.link_id 
WHERE l.link_is_click = 1