2010-05-19 86 views
0

如果我想從表'消息'中獲得結果,但排除了'messages_view'中的值,其中字段messages.message = messages_view.id AND messages.deleted = 1的行,則必須使用SQL查詢AND messages_view.user = $ somephpvariableMySQL從1個表中選擇結果,但根據另一個表排除結果?

在更外行而言,我有由「ID」以及與「消息」字段連接的messages_view表表示每個消息一個消息表。我想要獲取消息中未被刪除的行(來自messages_view)。消息被刪除時'刪除'= 1。

這裏是我當前的SQL查詢,只是得到的值出:

SELECT * FROM messages WHERE ((m_to=$user_id) 
    OR (m_to=0 AND (m_to_state='' OR m_to_state='$state') 
    AND (m_to_city='' OR m_to_city='$city'))) 

這裏是我的表的佈局:

table: messages 
---------------------------- 
id (INT) (auto increment) 
m_from (INT)      <-- Represents a user id (0 = site admin) 
m_to (INT)      <-- Represents a user id (0 = all users) 
m_to_state (VARCHAR) 
m_to_city (VARCHAR) 

table: messages_view 
---------------------------- 
message (INT)     <-- Corresponds to messages.id above 
user (INT)      <-- Represents a user id 
deleted (INT)     <-- 1 = deleted 

回答

0

我真的覺得這是像這樣簡單:

SELECT * FROM messages WHERE ((m_to=$user_id) 
    OR (m_to=0 AND (m_to_state='' OR m_to_state='$state') 
    AND (m_to_city='' OR m_to_city='$city'))) 
AND NOT EXISTS (
    SELECT * 
    FROM messages_view 
    WHERE messages.message = messages_view.id 
     AND messages.deleted = 1 
     AND messages_view.user = $somephpvariable 
) 
+0

乾杯!隨着一些擺弄,我得到它的工作,謝謝。 – Brandon 2010-05-19 04:12:50

0
Select ... 
From Messages M 
Where M.deleted = 0 
    And Not Exists (
        Select 1 
        From Messages_View MV1 
        Where MV1.message = messages_view.Id 
         And MV1.user = $somephpvariable 
        ) 

有與你的第一段和第二段的矛盾是你想要刪除的標誌。

相關問題