mysql 排除另一表,MySQL SELECT的结果来自1个表,但排除结果取决于另一个表?

该博客讨论了如何在SQL查询中从'messages'表中获取不包含已删除记录(deleted=1)且与'user'变量匹配的消息,同时排除了'messages_view'表中相应被标记为删除的消息。作者给出了现有的复杂查询并提出了可能的简化解决方案。
摘要由CSDN通过智能技术生成

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)

m_to (INT)

m_to_state (VARCHAR)

m_to_city (VARCHAR)

table: messages_view

----------------------------

message (INT)

user (INT)

deleted (INT)

解决方案

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

)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值