我寫了一個非常複雜的mysql查詢並在mysql工作臺中測試它,它工作得很好。但是當我在我的qt程序中使用這個查詢時,它不起作用。Mysql查詢在qt中不起作用
爲了獲得更好的分辨率,我有3個表格(產品,類別,產品類別),我想用parentId = 5和每個類別的2個產品獲取3個類別。這裏是我的功能:
void DbQueries::getFullCategories(int parent_id, int offset, int limit, int plimit)
{
...
QSqlQuery q;
q.prepare("set @num := 0, @cid := '';"
"SELECT e.ProductId, e.title, e.price, e.rate, e.rateAvg, e.imgUrl, d.cid, d.ctitle"
"FROM products e,"
"(SELECT ProductId, @num := if(@cid = categoryId, @num + 1, 1) as qty, @cid := categoryId as cid, title as ctitle"
"FROM ("
"SELECT b.ProductId, b.categoryId, a.title"
"FROM products_categories b, (SELECT catId, title FROM categories WHERE parentId = :parent_id LIMIT :limit OFFSET :offset) as a"
"WHERE b.categoryId = a.catId"
"ORDER BY b.categoryId"
") as c"
") as d"
"WHERE e.ProductId = d.ProductId AND d.qty <= :plimit"
"ORDER BY d.cid;");
q.bindValue(":parent_id", parent_id);
q.bindValue(":limit", limit);
q.bindValue(":offset", offset);
q.bindValue(":plimit", plimit);
if(!q.exec())
qDebug() << q.lastError().text();
const QSqlRecord &r = q.record();
qDebug() << r.count();
...
}
與此查詢,exec()
後,我沒有錯誤,但沒有記錄在我的QSqlRecord
牽強。我試圖在:=
之前放\
,並且我得到了Unknown escape sequence '\:'
。
當我我的查詢減少到這一點:
QSqlQuery q;
q.prepare("SELECT b.ProductId, b.categoryId, a.title"
"FROM products_categories b, (SELECT catId, title FROM categories WHERE parentId = :parent_id LIMIT :limit OFFSET :offset) as a"
"WHERE b.categoryId = a.catId"
"ORDER BY b.categoryId");
我有mysql的錯誤,如:"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'b, (SELECT catId, title FROM categories WHERE parentId = 5 LIMIT 3 OFFSE' at line 1 QMYSQL: Unable to execute query"
這有點混亂。重來。並參見http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-詢問 – Strawberry