2017-09-17 33 views
1
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表中的notification_by_business_account_id可能爲0。如果由業主發送,則不會有用戶名,所以我的查詢不會檢索這些通知。連接兩個表時可以使用OR嗎?

我的目標是檢索所有業務標識爲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測試商業。

回答

2

這是Left Outer Join的教科書示例,所以我建議您閱讀特定外連接的連接。請注意,單詞「outer」並不總是在代碼中拼寫出來,但「left join」與「left outer 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*/) 
相關問題