1

私はこのようなコードを持っています:

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?

4

2 に答える 2

2

コードが少ないわけではありませんが、answersテーブルを 2 回結合することでこれを行うこともできます。

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`;
于 2012-12-22T19:51:06.260 に答える
1

ONSQLに句がありません

これを試して

       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' 

ダブルである最後の行を削除しました

于 2012-12-22T19:53:13.883 に答える