Oracle SELECT WHERE 值存在或不存在
我有3张桌子; CASES
、USERS
和 USER_META
。对于这个问题,您需要知道USER_META
表有3列; user_id
、meta_key
和 meta_value
每个用户都与许多 CASES
和每个 USER
相关联与许多 USER_META
相关联
我当前的查询是这样的。
SELECT CASES.*, USERS.*, USER_META.*
FROM CASES
JOIN USERS ON USERS."user_id" = CASES."user_id"
JOIN USER_META ON USER_META_"user_id" = USERS."user_id"
这种方法的问题是每个用户都有大量 USER_META,所以我的结果集有太多行。如何重写此查询,以便我只能选择 USER_META,其中 USER_META."meta_key" 等于某个值但如果他们还没有设置此 USER_META."meta_key",仍然可以获得结果
:
SELECT CASES.*, USERS.*, USER_META.*
FROM CASES
JOIN USERS ON USERS."user_id" = CASES."user_id"
JOIN USER_META ON USER_META_"user_id" = USERS."user_id"
WHERE USER_META."meta_key" = 'my_key'
这会很好用,但并非所有用户在“meta_key”列中都有“my_key”值,我们仍然需要查看他们的 CASE。对于没有“meta_key”的用户,结果应该只返回 CASE 和 USER 列。
我如何重写此查询,以便它为使用此元密钥和不使用此元密钥的用户获取结果?
谢谢,我希望这是有道理的。
I have 3 tables; CASES
, USERS
and USER_META
. For this issue you need to know that the USER_META
table has 3 columns; user_id
, meta_key
and meta_value
Each user is associated with many CASES
and each USER
is associated with many USER_META
My current query is like this
SELECT CASES.*, USERS.*, USER_META.*
FROM CASES
JOIN USERS ON USERS."user_id" = CASES."user_id"
JOIN USER_META ON USER_META_"user_id" = USERS."user_id"
The problem with this approach is that each USER has A LOT of USER_META so my result set has too many rows. How can I rewrite this query so that I can select only the USER_META where the USER_META."meta_key" is equal to a certain value yet still get the result if they do not have this USER_META."meta_key" set yet
For example:
SELECT CASES.*, USERS.*, USER_META.*
FROM CASES
JOIN USERS ON USERS."user_id" = CASES."user_id"
JOIN USER_META ON USER_META_"user_id" = USERS."user_id"
WHERE USER_META."meta_key" = 'my_key'
This would work great but not all users have a value of "my_key" in the "meta_key" column and we still need to view their CASE. For users that do not have the "meta_key" the result should just return the CASE and USER columns.
How can I rewrite this query so it gets the result for both users with this meta_key and without?
Thanks, I hope this makes sense.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会使用 LEFT JOIN
I would use a LEFT JOIN
您需要对可能没有结果的表使用 OUTER JOIN。在 Oracle 中,在与该表的连接语句的字段名称附近使用 (+)。此链接可能对您有帮助: http://download.oracle .com/docs/cd/B28359_01/server.111/b28286/queries006.htm
you need to use OUTER JOIN with the table that may have no results. In Oracle, use (+) near to the field name of the join sentence with this table. This link may help you: http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/queries006.htm