简体   繁体   中英

How to construct MySQL view from query with UNIONs and sub-SELECTs

I'm trying to construct what seems like a common report to show me which lottery tickets I've played have numbers matching one or more of the announced winning draw. I have the below query which does exactly what I want from the SQL prompt. However, I need to express this as a VIEW so my single ODBC connection can access the two separate databases but I can't figure out how to set up the separate sub-views without still needing the UNIONs. Can anyone show me a better way? Guidance appreciated.

SELECT record_id, GROUP_CONCAT(num ORDER BY num) nums
FROM (
      SELECT record_id, n1 num FROM LA.tickets UNION
      SELECT record_id, n2 num FROM LA.tickets UNION
      SELECT record_id, n3 num FROM LA.tickets UNION
      SELECT record_id, n4 num FROM LA.tickets UNION
      SELECT record_id, n5 num FROM LA.tickets
     ) foo
    WHERE num = ANY ((SELECT n1 n FROM L.draw WHERE record_id = 1) UNION
                     (SELECT n2 n FROM L.draw WHERE record_id = 1) UNION
                     (SELECT n3 n FROM L.draw WHERE record_id = 1) UNION
                     (SELECT n4 n FROM L.draw WHERE record_id = 1) UNION
                     (SELECT n5 n FROM L.draw WHERE record_id = 1)
                )
    GROUP BY record_id
    HAVING count(*) >= 1;

(In this scenario, record #1 of the 'draw' table contains the 5 most-recently drawn numbers.

Well, a quick google of mysql create view brings me to http://dev.mysql.com/doc/refman/5.0/en/create-view.html which gives me the syntax like this (just copy/pasting your SELECT statement verbatim):

CREATE VIEW foo AS
SELECT record_id, GROUP_CONCAT(num ORDER BY num) nums
FROM (
      SELECT record_id, n1 num FROM LA.tickets UNION
      SELECT record_id, n2 num FROM LA.tickets UNION
      SELECT record_id, n3 num FROM LA.tickets UNION
      SELECT record_id, n4 num FROM LA.tickets UNION
      SELECT record_id, n5 num FROM LA.tickets
     ) foo
    WHERE num = ANY ((SELECT n1 n FROM L.draw WHERE record_id = 1) UNION
                     (SELECT n2 n FROM L.draw WHERE record_id = 1) UNION
                     (SELECT n3 n FROM L.draw WHERE record_id = 1) UNION
                     (SELECT n4 n FROM L.draw WHERE record_id = 1) UNION
                     (SELECT n5 n FROM L.draw WHERE record_id = 1)
                )
    GROUP BY record_id
    HAVING count(*) >= 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM