我有这样的代码:
SELECT
`cabinet`.`name_test`,
`answers`.`answer_id`,
(
SELECT `answer_id`
FROM `answers`
WHERE `user_id` = '353281' AND `answers`.`test_id` = `cabinet`.`test_id`
) as answer_2
FROM `cabinet`
INNER JOIN `answers`
WHERE
`user_id` = '184918649'
AND `friend_id` = '353281'
AND `answers`.`test_id` = `cabinet`.`test_id`
如何不写两次:answers
。test_id
= cabinet
。test_id
?
答案 0 :(得分:2)
代码不是很少,但你也可以通过两次加入answers
表来实现这一点:
SELECT
c.`name_test`,
a1.`answer_id` answer_1,
a2.`answer_id` answer_2
FROM `cabinet` c
INNER JOIN `answers` a1
ON c.`test_id` = a1.`test_id`
AND a1.`user_id` = '184918649'
AND `friend_id` = '353281'
INNER JOIN `answers` a2
ON c.`test_id` = a2.`test_id`
AND a2.`user_id` = '353281'
或者您可以使用子查询:
SELECT
c.`name_test`,
a1.`answer_id` answer_1,
a2.`answer_id` answer_2
FROM `cabinet` c
INNER JOIN
(
select `answer_id`
from `answers`
where `user_id` = '184918649'
AND `friend_id` = '353281'
) a1
ON c.`test_id` = a1.`test_id`
INNER JOIN
(
select `answer_id`
from `answers`
where `user_id` = '353281'
) a2
ON c.`test_id` = a2.`test_id`;
答案 1 :(得分:1)
你在sql中缺少ON
子句
试试这个
SELECT
`cabinet`.`name_test`,
`answers`.`answer_id`,
(
SELECT `answer_id`
FROM `answers`
WHERE `user_id` = '353281' AND `answers`.`test_id` = `cabinet`.`test_id`
) as answer_2
FROM `cabinet`
INNER JOIN `answers` on `answers`.`test_id` = `cabinet`.`test_id`
WHERE
`user_id` = '184918649'
AND `friend_id` = '353281'
删除了最后一行是双