开发者

MySQL SELECT results from 1 table, but exclude results depending on another table?

What SQL query would I have to use if I want to get the results from a table 'messages' but exclude rows that have the value in 'messages_view' where field messages.message=messages_view.id AND messages.deleted=1 AND messages_view.user=$somephpvariable

In more laymen terms, I have a messages table with each message denoted by an 'id' as well as a messages_view开发者_运维百科 table connected with a 'message' field. I want to get the rows in message that are not deleted (comes from messages_view) for a specific 'user'. 'deleted'=1 when the message is deleted.

Here is my current SQL Query that just gets the values out of :

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')))

Here is the layout of my tables:

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


I really think it's as simple as this:

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
)


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
                    )

There is a contradiction from your first paragraph and your second paragraph as to what you want with respect to the deleted flag.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜