[英]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.
我有以下查询,该查询恰好可以从SQL提示符下执行所需的操作。 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.
但是,我需要将此表示为VIEW,以便我的单个ODBC连接可以访问两个单独的数据库,但是我不知道如何在不需要UNION的情况下设置单独的子视图。 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. (在这种情况下,“绘制”表的记录#1包含5个最近绘制的数字。
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): 好吧,一个快速的
mysql create view
谷歌将我带到http://dev.mysql.com/doc/refman/5.0/en/create-view.html ,它给了我这样的语法(只需复制/粘贴您的SELECT
语句逐字):
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.