[英]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 如果我想从表“ messages”中获取结果,但要排除具有“ messages_view”中的值的行,则其中必须使用哪种SQL查询,其中fields.message = messages_view.id AND messages.deleted = 1 AND messages_view。用户= $ somephp变量
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. 用更多的外行术语来说,我有一个消息表,每个消息都由一个“ id”表示,还有一个message_view表与一个“ message”字段连接。 I want to get the rows in message that are not deleted (comes from messages_view ) for a specific 'user'. 我想为特定的“用户”获取未删除的消息行(来自messages_view )。 'deleted'=1 when the message is deleted. 删除邮件时,“已删除” = 1。
Here is my current SQL Query that just gets the values out of : 这是我当前的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')))
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. 您的第一段和第二段在关于已删除标志的要求方面存在矛盾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.