使用 if 条件从两个表中进行选择的 SQL 查询
我有两个表“通知”和“确认”。确认有一个字段保存通知表的主键。基本上一个通知会有很多确认。
Tables: Notification Acknowledgment
fields: id, notifier id, parent_id, status
现在我必须从通知中选择行,以便:
- 没有确认 WHERE Acknowledment.parent_id = notification.id (对于该特定通知基本上没有确认) //or
- if there is an Acknowledgment for notification, then select notification if any of the Acknowledgments withparent_id = notification.id has a Acknowledgment.status = someValue
伪 SQL 代码:
"SELECT * FROM Notification (WHERE id is not present in Acknowledgment.parent_id) OR
(WHERE id is present in Acknowledgment.parent_id AND Acknowledgment.status=@someValue"
我可以将其分解为更简单的查询并实现此目的,但我我很想知道一个查询来完成这项工作..
I have two tables Notification and Acknowledgment. Acknowledgment has a field which holds the primary key of Notification table. Basically a Notification will have many Acknowledgments.
Tables: Notification Acknowledgment
fields: id, notifier id, parent_id, status
Now I have to choose rows from Notification such that:
- there is no Acknowledgment WHERE Acknowledment.parent_id = Notification.id (basically no Acknowledgment for that particular Notification)
//or - if there is an Acknowledgment for Notification, then select Notification if any of the Acknowledgments with parent_id = Notification.id has a Acknowledgment.status = someValue
A pseudo SQL code:
"SELECT * FROM Notification (WHERE id is not present in Acknowledgment.parent_id) OR
(WHERE id is present in Acknowledgment.parent_id AND Acknowledgment.status=@someValue"
I can break it into simpler queries and achieve this, but I would love to know one single query to get this done..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
作为
LEFT OUTER JOINS
的替代方案,您可以使用EXISTS
子句。对于您的示例:
JOIN
在 SQL 中往往会得到更好的优化(特别是在我的示例中,您在同一个表上使用多个连接),我只是提到这种替代方案,因为它是一种更直接地翻译您的伪查询。As an alternative to
LEFT OUTER JOINS
, you can use theEXISTS
clause.For your example:
JOIN
s tend to be better optimized in SQL (particularly where, as in my example, you are using more than one on the same table), I just mention this alternative as it is a more direct translation of your pseudo-query.