如果我想从表'messages'获取结果,但我要使用哪些SQL查询,但排除在'messages_view'中具有值的行,其中字段messages.message = messages_view.id AND messages.deleted = 1 AND messages_view.user = $ somephpvariable
在更常见的情况下,我有一个消息表,其中每个消息由'id'表示,以及 messages_view 表与'message'字段相关联。我想获取特定“用户”未删除的消息中的行(来自 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 :(得分: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
)
答案 1 :(得分: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
)
您的第一段和第二段与您删除的旗帜相关的内容存在矛盾。