如果我有一个有两个选择的查询,我可以使用第二个选择中第一个选择的值吗?
即:
(SELECT post_id AS post_1 FROM posts WHERE user_id = 100) UNION (SELECT post_id AS post_2 FROM posts WHERE user_id = post_1)
上述方法不起作用,我该怎么办呢?
答案 0 :(得分:0)
这取决于您尝试做什么,您可以使用子查询来获取WHERE
子句的结果
例如
SELECT post_id AS post_2 FROM posts
WHERE user_id = (SELECT post_id AS post_1 FROM posts WHERE user_id = 100)
或者您可以按顺序运行两个查询,将第一个结果分配给变量并使用
例如
SET myVar = (SELECT post_id AS post_1 FROM posts WHERE user_id = 100);
SELECT post_id AS post_2 FROM posts WHERE user_id = myVar
答案 1 :(得分:0)
您好像正在寻找加入?
SELECT p1.post_id as post_id1
, p2.post_id as post_id2
FROM posts p1
JOIN posts p2
ON p2.user_id = p1.post_id
WHERE p1.user_id = 100;