加入两张桌子时可以使用OR吗?

时间:2017-09-17 01:16:02

标签: mysql sql database relational-database

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

在这种情况下,我正在尝试检索通知消息以及发出通知的员工的用户名。问题是,如果员工没有发送通知,则通知表中的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的业务。

1 个答案:

答案 0 :(得分:2)

这是Left Outer Join的教科书示例,因此我建议您阅读特定外连接中的连接。注意单词" outer"并不总是在代码中拼写,但是" left join"与"左外连接"相同。

以下是查询:

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*/)