繁体   English   中英

连接两个表时可以使用OR吗?

[英]Can I use OR when joining two tables?

SELECT Notifications.message, BusinessAccounts.employee_username
FROM Notifications, BusinessAccounts
WHERE Notifications.notification_by_business_account_id = BusinessAccounts.account_id AND Notifications.notification_business_id=5

在这种情况下,我试图在发送通知的员工的用户名旁边检索通知消息。 问题是,如果通知不是由员工发送的(而是由企业所有者自己发送的),则Notifications表中的notification_by_business_account_id可能为0。 如果由企业所有者发送,将没有用户名,因此我的查询不会检索这些通知。

我的目标是检索有关业务ID 5的所有通知。如果Notifications.notification_by_business_account_id设置为0(表示通知是由所有者发送的),我只想将account_username列中的值保留为空白。 我怎样才能做到这一点? 我会在某个地方使用OR吗? 这是我的桌子:

TABLE `Notifications` (
  `notification_id` mediumint(8) unsigned NOT NULL,
  `notification_business_id` mediumint(8) unsigned NOT NULL,
  `notification_by_business_account_id` int(10) unsigned NOT NULL COMMENT 'This id represents the id of the employee account that sent the notification. Set 0 if from business owner.',
  `notification_message` varchar(150) COLLATE utf8mb4_unicode_ci NOT NULL,
  `notification_date_sent` datetime NOT NULL
)

TABLE `BusinessAccounts` (
  `account_id` int(10) unsigned NOT NULL,
  `account_username` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
  `account_business_id` mediumint(8) unsigned NOT NULL
)

有多个业务。 我现在仅测试ID为5的业务。

这是左外部联接的教科书示例,因此我建议您阅读有关特定外部联接的联接。 请注意,“外部”一词并非总是在代码中拼写清楚,但“左连接”与“左外部连接”相同。

这是查询:

Select *
From Notifications As N
Left Outer Join BusinessAccounts As B
    On      N.notification_by_business_account_id = B.account_id 
Where N.notification_business_id In (5 /*List your business ID's separated by commas here if/when you have multiple*/)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM