我遇到MySQL查询问题。查询如下:
SET @catlocation = (SELECT id FROM categories WHERE url_name='hexcode');
SELECT
subs.display_name AS display,
subs.url_name AS url,
(
SELECT title
FROM threads
WHERE location = subs.id
ORDER BY time_submitted DESC
LIMIT 1
) AS title,
(
SELECT username
FROM users
WHERE uid = (
SELECT uid
FROM threads
WHERE location = subs.id
ORDER BY time_submitted DESC
LIMIT 1
)
LIMIT 1
) AS author,
(
SELECT COUNT(*)
FROM threads
WHERE location = subs.id
ORDER BY time_submitted DESC
LIMIT 1
) AS thread_count
FROM (
SELECT *
FROM categories
WHERE parent_id = @catlocation
) AS subs
当我尝试通过PHP运行时,我得到一个错误的结果和错误:
您的SQL语法有错误;查看与您的MySQL服务器版本相对应的手册,以便在
我不知道语法错误是什么,如果有人可以向我指出那将是非常好的。
编辑:这可能是由于有两个select语句(设置@catlocation
的语句和主查询吗?)
答案 0 :(得分:1)
在ansi SQL中,您需要为每个表声明一个标记,如果只有一个表,则省略它。尝试取出“线程”。到处都是,不需要
答案 1 :(得分:1)
您可以使用联接重构您的请求以提高性能。
SELECT s.display_name display, s.url_name url,
t1.title, u.username author,
COUNT(t2.title) total
FROM categories s
LEFT JOIN threads t1 ON t1.id = (SELECT id FROM threads
WHERE location = s.id
ORDER BY time_submitted DESC
LIMIT 1)
LEFT JOIN users u ON u.uid = t1.uid
LEFT JOIN threads t2 ON t2.location = s.id
WHERE s.parent_id = @catlocation
GROUP BY s.display_name, s.url_name, t1.title, u.username
答案 2 :(得分:1)
看来第一个设置@catlocation
的SELECT语句导致了问题。我将它移动到子查询中并成功执行查询
新查询如下:
SELECT categories.display_name display,
categories.url_name url,
threads.title title,
users.username author,
( SELECT COUNT(title)
FROM threads
WHERE location = categories.id
) total
FROM categories
LEFT JOIN threads
ON threads.tid = ( SELECT tid
FROM `threads`
WHERE location = categories.id
ORDER BY time_submitted DESC
LIMIT 1 )
LEFT JOIN users ON users.uid = threads.uid
WHERE categories.parent_id = ( SELECT id
FROM `categories`
WHERE url_name='hexcode'
LIMIT 1 );
我将继续使用JOIN重构查询(一旦我学会了如何使用它们)。感谢所有建议的修复,我不理解JOIN的答案,仍然无法正常运行。