从多个表中选择查询

时间:2012-05-20 05:58:25

标签: php mysql sql

我有6个表,需要从这些表中一次检索一些数据。任何机构都可以告诉我,我可以从一个查询中选择我的值。

我需要的这些价值。

institute_id
institute_name
city_name
options (relate to institute_id) 
mediums (relate to institute_Id)

这些来自我的表格

CREATE TABLE institutes (
    institute_id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT,
    login_id INT(4) UNSIGNED NOT NULL,
    address_id INT(4) NOT NULL,
    contact_id INT(4) NOT NULL,
    institute_code INT(4) NOT NULL, 
    institute_name VARCHAR(80) NOT NULL, 
    institute_details VARCHAR(80) NOT NULL, 
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE address (
    address_id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT,
    address_one VARCHAR(40) NOT NULL, 
    address_two VARCHAR(40) DEFAULT NULL, 
    city_id INT(4) UNSIGNED NOT NULL,
    PRIMARY KEY (address_id),
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE city(
    city_id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT,
    city_name VARCHAR(30) NOT NULL, 
    state_id INT(2) UNSIGNED NOT NULL,
    PRIMARY KEY (city_id),
) ENGINE=MyISAM;

CREATE TABLE medium(
    medium_id INT(2) UNSIGNED NOT NULL AUTO_INCREMENT,
    medium_name VARCHAR(30) NOT NULL, 
    PRIMARY KEY (medium_id),
) ENGINE=MyISAM;


CREATE TABLE options(
    option_id INT(2) UNSIGNED NOT NULL AUTO_INCREMENT,
    option_name VARCHAR(60) NOT NULL, 
    PRIMARY KEY (option_id),
) ENGINE=MyISAM;


CREATE TABLE institute_medium(
    im_id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT,
    medium_id INT(2) UNSIGNED NOT NULL,
    institute_id INT(4) UNSIGNED NOT NULL,
    PRIMARY KEY (im_id)
) ENGINE=MyISAM;

那些是我的桌子

我试过这样但是当我试图获得选项和媒介时我很困惑..在一个机构的instutite_medium中总有不止一个选项和媒介......

$query = "SELECT 
              institute_id, institute_name, city_name, 
              DATE_FORMAT(registration_date, '%M %e, %Y') AS date
          FROM 
              institutes 
          INNER JOIN 
              address ON institutes.address_id = address.address_id
          INNER JOIN 
              city ON address.city_id = city.city_id
          ORDER BY 
              registration_date DESC";

任何评论都非常感谢。

谢谢......

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

SELECT 
          institute_id, institute_name, city_name, 
          DATE_FORMAT(registration_date, '%M %e, %Y') AS date,
          GROUP_CONCAT(mediums.name SEPARATOR ', ')
      FROM 
          institutes 
      INNER JOIN 
          address ON institutes.address_id = address.address_id
      INNER JOIN 
          city ON address.city_id = city.city_id
      LEFT JOIN 
          institute_medium ON institutes.institute_id = institute_medium.institute_id
      LEFT JOIN 
          medium ON institute_medium.medium_id = medium.medium_id
      ORDER BY 
          registration_date DESC

GROUP_CONCAT(mediums.name SEPARATOR',')基本上会破坏所有媒体名称。

您可以删除组concat并使用mediums.names并使用右连接,然后您将多次使用相同的行,唯一的变体是中等名称