【问题标题】:Which table does the row come from?该行来自哪个表?
【发布时间】:2015-01-29 20:51:34
【问题描述】:

这是我的查询:

SELECT * 
FROM messages 
WHERE status = 1 
AND (
    poster IN (SELECT thing FROM follows WHERE follower = :uid AND type = 3) 
    OR 
    topic_id IN (SELECT thing FROM follows WHERE follower = :uid AND type = 1)
) 
ORDER BY post_date DESC LIMIT 0, 20

我想知道行来自哪个子句。来自poster IN (...) 部分还是topic_id IN (...) 部分?我该怎么做?

【问题讨论】:

    标签: mysql sql select where-clause


    【解决方案1】:

    一个简单的方法:

    SELECT *
         , CASE WHEN poster IN (SELECT thing FROM follows WHERE follower = :uid AND type = 3) THEN 'poster' 
                ELSE 'topic_id' END AS from_clause
    FROM messages <..>
    

    另一种方式:

    SELECT m.* 
         , CASE WHEN t1.thing IS NULL THEN 'topic_id' ELSE `poster` END AS from_clause
    FROM messages m 
    LEFT JOIN (SELECT thing FROM follows WHERE follower = :uid AND type = 3) t1 ON m.poster = t1.thing
    LEFT JOIN (SELECT thing FROM follows WHERE follower = :uid AND type = 1) t2 ON m.topic_id = t2.thing
    WHERE m.status = 1  AND (t1.thing IS NOT NULL OR t2.thing IS NOT NULL) 
    

    【讨论】:

    • 谢谢,但这不会减慢查询速度吗?让我试试。
    • @Wellenbrecher:嗯,它显然不会加快速度。
    • @Wellenbrecher :我已经发布了另一个,还没有测试过,但试一试。
    猜你喜欢
    • 2012-10-22
    • 2020-11-19
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    相关资源
    最近更新 更多