[英]MySQL - SELECT with LEFT JOIN optimization
I have 3 tables to select from. 我有3张桌子可供选择。 2 of them are always necessary ( tbl_notes
, tbl_clients
) while the 3rd is optional ( tbl_notes_categories
). 它们中的2个总是必需的( tbl_notes
, tbl_clients
),而第3个是可选的( tbl_notes_categories
)。
I've always used a LEFT JOIN
in my queries with questionable correlating records to the primary table. 我一直在查询中使用LEFT JOIN
并将可疑的相关记录关联到主表。
But I'm not getting any results with the query below. 但是我在下面的查询中没有得到任何结果。
Would someone point out how I'm using the LEFT JOIN incorrectly? 有人会指出我如何错误地使用LEFT JOIN吗?
SELECT n.*, c.clientname, nc.notecategoryname
FROM tbl_notes n, tbl_clients c
LEFT JOIN tbl_notes_categories nc ON n.categoryid = nc.categoryid
WHERE n.clientid = c.clientid
AND c.clientid = 12345
ORDER BY n.dateinserted DESC
In fact, I'm getting a sql error. 实际上,我遇到了sql错误。 #1054 - Unknown column 'n.categoryid' in 'on clause' #1054-'on子句'中的未知列'n.categoryid'
categoryid
certainly does exist in tbl_notes
categoryid
当然存在于tbl_notes
I probably need to brush up on how JOINS really work. 我可能需要重新研究JOINS的实际工作方式。 I'm guessing I cannot have a LEFT JOIN with 2 database tables before it? 我猜我之前不能有2个数据库表的LEFT JOIN吗?
On a side note, I can foresee times when there will be multiple required tables, with several optional tables. 附带一提,我可以预见何时会有多个必需表和几个可选表。 (in this case tbl_notes_categories
is optional) (在这种情况下, tbl_notes_categories
是可选的)
Assuming the column categoryid
exists in the tbl_notes
table... 假设列categoryid
tbl_notes
存在于tbl_notes
表中...
Try rewriting the query to use the JOIN
syntax, rather than using the old-school comma as the join operator. 尝试重写查询以使用JOIN
语法,而不是使用老式的逗号作为JOIN
运算符。 (If the problem isn't a misnamed column, I suspect the problem is in mixing the two types of syntax... but this is just a suspicion, I have no reason to test mixing old-style comma joins with JOIN
keywords.) (如果问题不是列的名称错误,我怀疑问题在于两种语法的混合使用……但这只是一种怀疑,我没有理由测试将老式逗号连接与JOIN
关键字混合使用。)
I'd write the statement like this: 我将这样写语句:
SELECT n.*, c.clientname, nc.notecategoryname
FROM tbl_notes n
JOIN tbl_clients c
ON n.clientid = c.clientid
LEFT
JOIN tbl_notes_categories nc
ON nc.categoryid = n.categoryid
WHERE c.clientid = 12345
ORDER BY n.dateinserted DESC
(Actually, I would specify the individual columns to return from n
, rather than using n.*
, but that's just a style preference, not a SQL syntax requirement.) (实际上,我会指定要从n
返回的各个列,而不是使用n.*
,但这只是样式首选项,而不是SQL语法要求。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.