如何通过从另一个表中选择一行来检索数据表单

时间:2016-03-15 12:50:37

标签: mysql sql phpmyadmin

我有两张这样的表

enter image description here

我希望编写SQL查询,在所有者为John时检索FORD,MAZDA,TOYOTA 和另一个SQL查询,当所有者是约瑟夫时,检索MITSUBISHI,JEEP,HONDA。

我能这样做吗?

你能帮帮我吗?

3 个答案:

答案 0 :(得分:0)

这是多对多的关系 看看这个: http://www.tomjewett.com/dbdesign/dbdesign.php?page=manymany.php

答案 1 :(得分:0)

您需要添加数据透视表以将这两种实体类型连接在一起。 但首先你需要每个表的主键。

companies
---------
id   PRIMARY KEY AUTO_INCREMENT
name VARCHAR NOT NULL UNIQUE

owners
------
id   PRIMARY KEY AUTO_INCREMENT
name VARCHAR NOT NULL UNIQUE

现在是支点

companies_owners
----------------
company INT NOT NULL REFERENCES companies
owner   INT NOT NULL REFERENCES owners

数据透视表还应在companyowner

上设置唯一索引

答案 2 :(得分:0)

在phpmyadmin中执行这些表并将其导入数据库

for (var i = 0; i <= 20; i+=5) {
  console.log(i);
}

然后执行此查询

 -- phpMyAdmin SQL Dump
-- version 4.1.14
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Mar 15, 2016 at 02:06 PM
-- Server version: 5.6.17
-- PHP Version: 5.5.12

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `cars`
--

CREATE TABLE IF NOT EXISTS `cars` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `owner_id` text NOT NULL,
  `car` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

--
-- Dumping data for table `cars`
--

INSERT INTO `cars` (`id`, `owner_id`, `car`) VALUES
(1, '1255', 'FORD'),
(2, '1255', 'MAZDA'),
(3, '1255', 'TOYOTA'),
(4, '1455', 'MITSUBISHI'),
(5, '1455', 'JEEP'),
(6, '1455', 'HONDA');

-- --------------------------------------------------------

--
-- Table structure for table `owners`
--

CREATE TABLE IF NOT EXISTS `owners` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `owner_id` text NOT NULL,
  `owner` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

--
-- Dumping data for table `owners`
--

INSERT INTO `owners` (`id`, `owner_id`, `owner`) VALUES
(1, '1255', 'Jhon'),
(2, '1455', 'Joseph');

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

现在您将了解完成所要求的基本方式