0

表结构: 在此处输入图像描述

SELECT p.id id, p.type
    TYPE , v.provider provider, v.video_id video_id, NULL content, NULL url, NULL posted_by
    FROM post p
    INNER JOIN p_video v ON p.id = v.id
    AND p.type =  'video'
    UNION 
    SELECT p.id, p.type, NULL , NULL , t.content, NULL , NULL 
    FROM post p
    INNER JOIN p_text t ON p.id = t.id
    AND p.type =  'text'
    UNION 
    SELECT p.id, p.type, NULL , NULL , NULL , i.url, NULL 
    FROM post p
    INNER JOIN p_image i ON p.id = i.id
    AND p.type =  'image'
    UNION 
    SELECT p.id, p.type, NULL , NULL , NULL , l.url, NULL 
    FROM post p
    INNER JOIN p_link l ON p.id = l.id
    AND p.type =  'link'
    UNION 
    SELECT p.id, NULL , NULL , NULL , NULL , NULL , u.name
    FROM post p
    LEFT JOIN user u ON p.user_id = u.id
    ORDER BY id DESC 
    LIMIT 0 , 30

我的 SQL 输出

我的语法错误是什么?它只做 2 行.. 但我希望所有输出都在单独的 1 行中。

4

2 回答 2

1

尝试这个

SELECT p.id id, p.type
TYPE , v.provider provider, v.video_id video_id, NULL content, NULL url, u.name posted_by
FROM post p
LEFT JOIN user u ON p.user_id = u.id
INNER JOIN p_video v ON p.id = v.id
AND p.type =  'video'
UNION 
SELECT p.id, p.type, NULL , NULL , t.content, NULL , u.name
FROM post p
LEFT JOIN user u ON p.user_id = u.id
INNER JOIN p_text t ON p.id = t.id
AND p.type =  'text'
UNION 
SELECT p.id, p.type, NULL , NULL , NULL , i.url, u.name
FROM post p
LEFT JOIN user u ON p.user_id = u.id
INNER JOIN p_image i ON p.id = i.id
AND p.type =  'image'
UNION 
SELECT p.id, p.type, NULL , NULL , NULL , l.url, u.name
FROM post p
LEFT JOIN user u ON p.user_id = u.id
INNER JOIN p_link l ON p.id = l.id
AND p.type =  'link'
ORDER BY id DESC 
LIMIT 0 , 30
于 2012-12-08T18:11:19.143 回答
0

这是您的最后一个联合选择,它添加了第二行。如果您想在每一行中添加左连接,则将左连接添加到每个联合选择部分并省略最后一个联合选择

SELECT p.id id, p.type
TYPE , v.provider provider, v.video_id video_id, NULL content, NULL url, u.name posted_by
FROM post p
INNER JOIN p_video v ON p.id = v.id
AND p.type =  'video'
LEFT JOIN user u ON p.user_id = u.id
UNION 
SELECT ...
...
ORDER BY id DESC 
LIMIT 0 , 30
于 2012-12-08T18:12:24.057 回答