我正在开发一个彩票应用程序,我想检查用户票上的任何数字是否匹配任何已经绘制的球,每场比赛得2分。到目前为止,我有以下查询:
SELECT firstName, SUM(points) AS totalPoints FROM (
(SELECT userID, firstName, 2 * COUNT(*) AS points
FROM DRAWS NATURAL JOIN TICKETS NATURAL JOIN USERS
WHERE
number1 = ball1 OR
number1 = ball2 OR
number1 = ball3 OR
number1 = ball4
GROUP BY userID, drawID) AS N1
UNION ALL
(SELECT userID, firstName, 2 * COUNT(*) AS points
FROM DRAWS NATURAL JOIN TICKETS NATURAL JOIN USERS
WHERE
number2 = ball1 OR
number2 = ball2 OR
number2 = ball3 OR
number2 = ball4
GROUP BY userID, drawID) AS N2
UNION ALL
(SELECT userID, firstName, 2 * COUNT(*) AS points
FROM DRAWS NATURAL JOIN TICKETS NATURAL JOIN USERS
WHERE
number3 = ball1 OR
number3 = ball2 OR
number3 = ball3 OR
number3 = ball4
GROUP BY userID, drawID) AS N3 ) AS TOT
GROUP BY userID;
MySQL说:文档
1064 - 您的SQL语法出错;检查与您的MySQL服务器版本对应的手册,以便在AS&N2附近使用正确的语法
UNION ALL
(SELECT userID,firstName,2 * COUNT(*)AS points
来自DRA'在第18行
表的结构如下:
CREATE TABLE USERS (
userID INTEGER PRIMARY KEY,
firstName CHAR(16),
lastName CHAR(16),
email CHAR(32) UNIQUE,
phone CHAR(16),
userName CHAR(20),
passWord CHAR(20),
balance INTEGER );
CREATE TABLE TICKETS (
ticketID INTEGER PRIMARY KEY,
userID INTEGER,
drawID INTEGER,
date DATE,
number1 INTEGER,
number2 INTEGER,
number3 INTEGER,
score INTEGER,
prize INTEGER);
CREATE TABLE DRAWS (
drawID INTEGER PRIMARY KEY,
dateOpen DATE,
dateClose DATE,
gameID INTEGER,
ball1 INTEGER,
ball2 INTEGER,
ball3 INTEGER,
ball4 INTEGER,
bonusBall INTEGER,
dateDrawn DATE,
profit INTEGER,
charityID INTEGER );
我认为我的UNION存在问题,因为个别查询工作正常。我一直试图解决这个问题,我不能这样做所以我想我会问专业人士。有什么建议吗?
答案 0 :(得分:1)
删除括号&自UNION ALL
以来的别名,与join不同,将多个SELECT
语句的结果合并到一个结果集中:
SELECT firstName, SUM(points) AS totalPoints FROM
(SELECT userID, firstName, 2 * COUNT(*) AS points
FROM DRAWS NATURAL JOIN TICKETS NATURAL JOIN USERS
WHERE
number1 = ball1 OR
...
GROUP BY userID, drawID
UNION ALL
SELECT userID, firstName, 2 * COUNT(*) AS points
FROM DRAWS NATURAL JOIN TICKETS NATURAL JOIN USERS
WHERE
number2
...
) AS Tot