Mysql
讓查詢在 SQLite 和 MySQL 上工作
我在主查詢 where 子句中有一個帶有條件的子查詢。
這是範例架構
CREATE TABLE `payments` ( `id` int(11) NOT NULL, `discount_id` int(11), `amount` int(11) ); CREATE TABLE `discounts` ( `id` int(11) NOT NULL, `rate` int(11) NOT NULL );
和查詢
SELECT discounts.*, (SELECT COUNT(id) FROM payments WHERE payments.discount_id = discounts.id GROUP BY payments.discount_id) AS usage_count FROM discounts WHERE rate > 10 AND usage_count > 1
- 在 SQLite 上工作:http ://sqlfiddle.com/#!5/9f159/2
- 不適用於 MySQL:http ://sqlfiddle.com/#!9/9f1593/1
MySQL顯示錯誤
Unknown column 'usage_count' in 'where clause'
我可以使用一個
HAVING
子句讓它在 MySQL 上工作,但是它在 SQLite 上失敗了TypeError: e.STATEMENT is undefined
- 不適用於 SQLite:http ://sqlfiddle.com/#!5/9f159
- 在 MySQL 上工作:http ://sqlfiddle.com/#!9/9f1593/2
有沒有一種方法可以同時使用兩者?
為什麼?我正在使用 Laravel 框架進行開發,我們的單元測試在 SQLite 上執行,應用伺服器執行 MySQL。
或者作為連接,因為您的子查詢只是一個 JOIN 並且 where 僅基於折扣。
SELECT discounts.*, count(*) as usage_count FROM discounts JOIN payments ON payments.discount_id = discounts.id WHERE rate > 10 GROUP BY payments.discount_id HAVING usage_count > 1
SELECT * FROM (SELECT discounts.*, (SELECT COUNT(id) FROM payments WHERE payments.discount_id = discounts.id GROUP BY payments.discount_id) AS usage_count FROM discounts WHERE rate > 10) table1 WHERE usage_count > 1