我需要使用join的两个select语句的帮助

时间:2011-05-23 16:16:30

标签: sql join

以下是我想要的两个陈述:

SELECT pictures.picture, users.fname, users.lname, users.email, users.phone
FROM users, pictures
WHERE users.userid = 1
AND pictures.userid = users.userid;

SELECT pictures.picture, users.fname, users.lname, posts.post, 'post' AS 
type
FROM users, posts, pictures
WHERE users.userid = posts.userid
AND posts.postid > 0
AND users.userid =1
AND pictures.userid = users.userid
GROUP BY time

以前我一直在使用UNION语句,但在这种情况下我不能这样做,因为两个语句中的列数不匹配。

提前致谢。

4 个答案:

答案 0 :(得分:1)

如果您使列列表匹配,则可以使用UNION。例如:

SELECT pictures.picture, users.fname, users.lname, users.email, users.phone, NULL, NULL
FROM users, pictures
WHERE users.userid = 1
AND pictures.userid = users.userid
UNION ALL
SELECT pictures.picture, users.fname, users.lname, NULL, NULL, posts.post, 'post' AS 
type
FROM users, posts, pictures
WHERE users.userid = posts.userid
AND posts.postid > 0
AND users.userid =1
AND pictures.userid = users.userid
GROUP BY time

答案 1 :(得分:1)

SELECT p.picture, u.fname, u.lname, u.email, u.phone, p.post, 'post' AS type
FROM users u
LEFT JOIN posts p ON u.userid = p.userid
LEFT JOIN pictures pic ON pic.user_id = u.userid
WHERE u.userid = 1
GROUP BY time

如果您需要结果集中的帖子或图片,则可以将LEFT JOIN更改为INNER JOIN

答案 2 :(得分:1)

SELECT pictures.picture, users.fname, users.lname, posts.post, 
       'post' AS type, users.email, users.phone
FROM users 
INNER JOIN pictures ON users.userid = pictures.userid
INNER JOIN posts on users.userid = posts.userid
WHERE users.userid = 1
AND posts.postid > 0
GROUP BY time;

答案 3 :(得分:0)

这可能是一个愚蠢的问题,我可能不理解某些事情,但为什么你需要两个陈述?

SELECT pictures.picture, users.fname, users.lname, 
FROM users, pictures
WHERE users.userid = 1
AND pictures.userid = users.userid;

SELECT pictures.picture, users.fname, users.lname, posts.post, 
    'post' AS type, users.email, users.phone
FROM users
LEFT JOIN posts ON (posts.userid = users.userid AND posts.postid > 0)
LEFT JOIN pictures (pictures.userid = users.userid)
WHERE users.userid =1
GROUP BY time

希望有所帮助。