我正在查询mysql数据库。我有3张桌子:
官
id | first | last
------------------
1 | jim | smith
2 | john | Doe
3 | larry | toad
4 | Dave | Charles
游戏
id | gm_date | league | REF | UMP
--------------------------------
1 | 2015-03-27 | 1 | 4 |
2 | 2015-03-28 | 1 | |
3 | 2015-03-29 | 1 | |
4 | 2015-04-01 | 1 | | 2
活动
id | date | league | off |
--------------------------------
1 | 2015-03-27 | 1 | 1 |
2 | 2015-03-28 | 1 | |
3 | 2015-03-29 | 1 | |
4 | 2015-04-01 | 1 | |
我想查询游戏表和事件表的查询,以查看给定日期的id是否存在。如果它在一个或两个中,我想返回true。
到目前为止,这是我的查询,但它似乎并没有起作用。
SELECT id , first , last
FROM officials AS o
WHERE o.id = 4 &&
EXISTS (
SELECT *
FROM games AS g
WHERE g.REF = o.id && g.gm_date = '2015-03-27' && g.league = 1
) ||
EXISTS (
SELECT *
FROM events as e
WHERE e.off = o.id && e.date = '2015-03-27' && e.league = 1
)
它返回日期的所有ID,而不是我请求的ID。
非常感谢任何帮助。我希望我描述得足够好吗?
答案 0 :(得分:0)
也许是这样的:
SELECT
id ,
first ,
last
FROM officials AS o
WHERE o.id = 4
AND
(
SELECT
NULL
FROM
games AS g
WHERE
g.REF = o.id
AND g.gm_date = '2015-03-27'
AND g.league = 1
UNION ALL
SELECT
NULL
FROM
events as e
WHERE
e.off = o.id
AND e.date = '2015-03-27'
AND e.league = 1
)
答案 1 :(得分:0)
也许:似乎奇怪的是你并没有在游戏桌上看UMP。 我使用了连接而不是存在,因此您需要返回有关游戏或事件的其他数据。
SELECT o.id, o.first, o.last
FROM officials o
LEFT JOIN Games g
on g.Ref = O.id
and g.gm_date = '2015-03-27'
and g.league = 1
LEFT JOIN Events e
on e.Off = O.Id
and e.league = 1
and e.date = '2015-03-27'
GROUP BY o.id, o.first, o.last
答案 2 :(得分:0)
我猜你想要所有ID为4的官员games
或events
中存在相应的行。如果是这样,那么你
需要围绕您的存在条件的括号,因为没有括号,查询将返回官方ID为4且games
中存在相应行的所有行以及官方(具有任何id)在{{中具有相应行的所有行1}}
events
答案 3 :(得分:0)
我认为你被 AND
和 OR
逻辑运算符之间的优先顺序所困扰。
SELECT 0 AND 1 OR 1
, (0 AND 1) OR 1
, 0 AND (1 OR 1)
在AND / OR条件周围添加parens允许您明确指定您希望它们评估的优先顺序。
答案 4 :(得分:-1)
这是一个似乎有效的查询。
SELECT
id ,
first ,
last
FROM officials AS o
WHERE o.id = 4
AND
(
SELECT
g.REF
FROM
games AS g
WHERE
g.REF = o.id
AND g.gm_date = '2015-03-27'
AND g.league = 1
UNION ALL
SELECT
e.off
FROM
events as e
WHERE
e.off = o.id
AND e.date = '2015-03-27'
AND e.league = 1
)