2016-03-16 59 views
0

我試圖確定可以接收藥物的用戶產生交互作用。對於我已經使用這個代碼:諮詢子查詢和使用正則表達式

SELECT c.user, COUNT(DISTINCT c.user) 
FROM mytable AS c 
    JOIN (SELECT id_beneficiario, mes 
     FROM mytable 
     WHERE codigo_atc REGEXP 'C01BD01|N06AA09|J01FA10|J01MA02|J01FA09|N05AH02|L01XE06|R06AA02|A03FA03| 
     L04AA27|J02AC01|N06AB03|C03CA01|N05AD01|C03AA03|J02AB02|J01MA12|N05AN01|J01XD01|J05AE04|L01XE08| 
     N05AH03|N05AH04|N05AX08|J05AE03|J05AE01|C07AA07|L04AD02|M03BX02|N06AX05|J01EE03') AS d 
ON c.user = d.user AND c.mes = d.mes 
WHERE (c.codigo_atc REGEXP 'C01BD01|N06AA09|J01FA10|J01MA02|J01FA09|N05AH02|L01XE06|R06AA02|A03FA03| 
     L04AA27|J02AC01|N06AB03|C03CA01|N05AD01|C03AA03|J02AB02|J01MA12|N05AN01|J01XD01|J05AE04|L01XE08| 
     N05AH03|N05AH04|N05AX08|J05AE03|J05AE01|C07AA07|L04AD02|M03BX02|N06AX05|J01EE03') 
GROUP BY c.user; 

我工作的地方和請教花費太多的時間和衝擊片雷管的下一個錯誤:錯誤代碼:查詢期間失去的2013年到連接如MySQL服務器。將可能優化我的代碼,以避免錯誤?

回答

0

這可以幫你嗎?

WHERE codigo_atc IN ('C01BD01','N06AA09','J01FA10','J01MA02','J01FA09', 
        'N05AH02','L01XE06','R06AA02','A03FA03','L04AA27', 
        'J02AC01','N06AB03','C03CA01','N05AD01', etc) 

如果codigo_atc匹配任何在(list)值的這IN子句將返回true。

SQL在設置邏輯上比在正則表達式匹配時要好得多。

+0

謝謝。該諮詢花了361189秒,但它的工作! –

+0

這是四天以上!您可能需要考慮在表格中添加一些索引。閱讀:http://use-the-index-luke.com/ –

0

您可以用in代替regexp嘗試.. 莫非這是更高性能的

SELECT c.user, COUNT(DISTINCT c.user) 
FROM mytable AS c 
JOIN (SELECT id_beneficiario, mes 
    FROM mytable 
    WHERE codigo_atc IN ('C01BD01','N06AA09','J01FA10','J01MA02','J01FA09','N05AH02','L01XE06','R06AA02','A03FA03',' 
    L04AA27','J02AC01','N06AB03','C03CA01','N05AD01','C03AA03','J02AB02','J01MA12','N05AN01','J01XD01','J05AE04','L01XE08',' 
    N05AH03','N05AH04','N05AX08','J05AE03','J05AE01','C07AA07','L04AD02','M03BX02','N06AX05','J01EE03') AS d 
ON c.user = d.user AND c.mes = d.mes 
WHERE c.codigo_atc IN ('C01BD01','N06AA09','J01FA10','J01MA02','J01FA09','N05AH02','L01XE06','R06AA02','A03FA03',' 
    L04AA27','J02AC01','N06AB03','C03CA01','N05AD01','C03AA03','J02AB02','J01MA12','N05AN01','J01XD01','J05AE04','L01XE08',' 
    N05AH03','N05AH04','N05AX08','J05AE03','J05AE01','C07AA07','L04AD02','M03BX02','N06AX05','J01EE03') 
GROUP BY c.user; 

,但如果你解釋你的相關表格的架構,並且希望獲得可以是可能的編寫更簡單的是什麼查詢