该行来自哪个表?

时间:2015-01-29 20:51:34

标签: mysql sql select where-clause

这是我的问题:

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 (...)部分?我怎么能这样做?

1 个答案:

答案 0 :(得分: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)