如何执行此查询

时间:2012-03-12 00:44:11

标签: mysql sql

我在尝试获取此类查询时遇到问题

表格答案

CREATE TABLE IF NOT EXISTS `rws_answers` (
  `id_answer` int(11) NOT NULL AUTO_INCREMENT,
  `id_question` int(11) DEFAULT NULL,
  `row_subject` varchar(255) NOT NULL,
  `column_subject` varchar(255) DEFAULT NULL,
  `answer_type` varchar(1) DEFAULT NULL,
  `score` int(5) DEFAULT '0',
  PRIMARY KEY (`id_answer`),
  KEY `IDX_51C8C33DE62CA5DB` (`id_question`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=765 ;

表评论

CREATE TABLE IF NOT EXISTS `rws_reviews` (
  `id_review` int(11) unsigned NOT NULL,
  `id_client` varchar(36) NOT NULL DEFAULT '',
  `id_item` int(11) unsigned NOT NULL DEFAULT '0',
  `id_question` int(11) unsigned NOT NULL DEFAULT '0',
  `id_location` int(11) unsigned NOT NULL DEFAULT '0',
  `id_answer` int(11) unsigned NOT NULL DEFAULT '0',
  `value` text,
  `date_answered` datetime NOT NULL,
   PRIMARY KEY (`id_review`,`id_client`,`id_item`,`id_question`,`id_location`,`id_answer`),
  KEY `IDX_6868EE34943B391C` (`id_item`),
  KEY `IDX_6868EE34E62CA5DB` (`id_question`),
  KEY `IDX_6868EE34E45655E` (`id_location`),
  KEY `IDX_6868EE34FCEAFFC8` (`id_answer`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

我需要的是获得表格答案中的所有id_answer,这些表格是否在表格评论中 所以,如果我尝试这个sql

SELECT r.id_review, a.id_answer AS aa, r.id_answer AS ra, a.row_subject, r.id_location
FROM rws_answers a 
LEFT JOIN rws_reviews r USING(id_answer)
ORDER BY a.id_answer DESC

我得到那些行,但因为review表可以有不同的id_location我需要过滤它们所以我添加到查询这个

SELECT r.id_review, a.id_answer AS aa, r.id_answer AS ra, a.row_subject, r.id_location
FROM rws_answers a 
LEFT JOIN rws_reviews r USING(id_answer)
WHERE r.id_location = 1
ORDER BY a.id_answer DESC

但是我所有不在评论表中的答案都不再显示了,我尝试了任何一种没有结果的组合,任何人都可以如此善良地试图帮助我或者建议我采用不同的方式做查询,我有超过3天的尝试,准备,做例子,不知道还能做什么,谢谢!

2 个答案:

答案 0 :(得分:1)

您可以将USING子句转换为ON子句,并将WHERE子句合并到其中:

LEFT JOIN rws_reviews r ON r.id_answer = a.id_answer AND r.id_location = 1

答案 1 :(得分:1)

尝试以下

SELECT r.id_review, a.id_answer AS aa, r.id_answer AS ra, a.row_subject, r.id_location
FROM rws_answers a 
LEFT JOIN rws_reviews r 
on r.id_answer = a.id_answer
and r.id_location = 1
ORDER BY a.id_answer DESC