0

我有 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";

非常感谢任何评论。

谢谢你...

4

1 回答 1

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

Will GROUP_CONCAT(mediums.name SEPARATOR ', ')基本上会内爆所有的媒体名称。

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

于 2012-05-20T06:20:05.797 回答