在一个查询中从同一列中选择两个不同的字段,

时间:2011-01-28 00:25:29

标签: mysql select join field

我有两张桌子:

CREATE TABLE sections (id int, section_name varchar(16), section_title int, section_description int);
INSERT INTO sections VALUES(1, 'index', 1, 2);
INSERT INTO sections VALUES(2, 'contact', 3, 4);

CREATE TABLE texts (id int, text_value varchar(64), text_language varchar(2), text_link int);
INSERT INTO texts VALUES(1, 'Home', 'en', 1);
INSERT INTO texts VALUES(2, 'Inicio', 'es', 1);
INSERT INTO texts VALUES(3, 'Welcome', 'en', 2);
INSERT INTO texts VALUES(4, 'Bienvenidos', 'es', 2);
INSERT INTO texts VALUES(5, 'Contact', 'en', 3);
INSERT INTO texts VALUES(6, 'Contacto', 'es', 3);
INSERT INTO texts VALUES(7, 'Contact Us', 'en', 4);
INSERT INTO texts VALUES(8, 'Contactenos', 'es', 4);

我是查询的新手,我不知道下一步该怎么做:

SELECT `sections`.`section_title`
     , `sections`.`section_description`
FROM `sections`
    INNER JOIN `texts`
    ON (`sections`.`section_title` = `texts`.`text_link`) AND (`sections`.`section_description` = `texts`.`text_link`)
    WHERE `sections`.`section_name` = 'index' AND `texts`.`text_language` = 'en'
;

MySQL返回一个空结果集:(

我希望使用sectionssection_name ='index'和texts获得。text_language ='en':

section_title = 'Home'
section_description = 'Welcome'

或使用sectionssection_name ='联系'和textstext_language ='es':

section_title = 'Contacto'
section_description = 'Contactenos'

2 个答案:

答案 0 :(得分:1)

你需要join两次......就像这样:

SELECT
  t1.text_value AS section_title,
  t2.text_value AS section_description
FROM `sections`
  INNER JOIN `texts` AS t1
    ON (`sections`.`section_title` = t1.`text_link`)
  INNER JOIN `texts` AS t2
    ON (`sections`.`section_description` = t2.`text_link`)
WHERE `section_name` = 'index'
    AND t1.`text_language` = 'en'
    AND t2.`text_language` = 'en'

答案 1 :(得分:1)

我对上面的查询进行了一些编辑,但是要做出评论的声望很低= P再试一次(对我有用):

SELECT t1.text_value AS section_title, 
       t2.text_value AS section_description
  FROM `sections` AS s
INNER JOIN `texts` as t1 ON (s.`section_title` = t1.`text_link`)
INNER JOIN `texts` as t2 ON (s.`section_description` = t2.`text_link`)
     WHERE s.`section_name` = 'index' 
       AND t1.`text_language` = 'en' 
       AND t2.`text_language` = 'en'
相关问题