如何根据某些列多次选择mysql记录并在表中显示?

时间:2017-03-17 19:16:45

标签: mysql database

我有一张这样的桌子:

id, name, date1, qty1, note1, date2, qty2, note2, date3, qty3, note3, admin

一些示例记录:

1, something , 03-17-2017, 20, wow ,           ,   ,    ,           ,   ,     , greg
2, nothing   , 03-17-2017, 25, hmm , 03-18-2017, 26, ok ,           ,   ,     , dave
3, everything, 03-17-2017, 30, cool, 03-18-2017, 31, yup, 03-19-2017, 32, nice, john

那么,如果我想显示这样的数据,我的选择语句会如何?

id | name       | date       | qty | note | admin
-------------------------------------------------
1  | something  | 03-17-2017 | 20  | wow  | greg
2  | nothing    | 03-17-2017 | 25  | hmm  | dave
2  | nothing    | 03-18-2017 | 26  | ok   | dave 
3  | everything | 03-17-2017 | 30  | cool | john
3  | everything | 03-18-2017 | 31  | yup  | john
3  | everything | 03-19-2017 | 32  | nice | john

所以,如果#2& #3列,然后记录显示一次。 如果#3列中没有值,则记录显示两次。 如果#1,#2和#3列有数据,则记录显示为3行。 当记录显示​​为2行或更多行时,每行应具有相同的值和一些不同的值。

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for jobs
-- ----------------------------
DROP TABLE IF EXISTS `jobs`;
CREATE TABLE `jobs` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `admin` varchar(100) NOT NULL,
  `name` varchar(100) NOT NULL,
  `date1` varchar(50) NOT NULL,
  `note1` varchar(255) NOT NULL,
  `qty1` varchar(50) NOT NULL,
  `date2` varchar(50) NOT NULL,
  `note2` varchar(255) NOT NULL,
  `qty2` varchar(50) NOT NULL,
  `date3` varchar(50) NOT NULL,
  `note3` varchar(255) NOT NULL,
  `qty3` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

-- ----------------------------
-- Records of jobs
-- ----------------------------
INSERT INTO `jobs` VALUES ('1', 'greg', 'something', '03-17-2017', 'wow', '20', '', '', '', '', '', '');
INSERT INTO `jobs` VALUES ('2', 'dave', 'nothing', '03-17-2017', 'hmm', '25', '03-18-2017', '26', 'ok', '', '', '');
INSERT INTO `jobs` VALUES ('3', 'john', 'everything', '03-17-2017', 'cool', '30', '03-18-2017', '31', 'yup', '03-19-2017', '32', 'nice');
SET FOREIGN_KEY_CHECKS=1;

3 个答案:

答案 0 :(得分:1)

尝试这样的查询,但在你的帖子中创建不正确,我几乎可以肯定插入也改变了字段。

SELECT id, `name`, date1, qty,note,admin
FROM(

    SELECT id, 1 AS subid, `NAME`, date1 AS date1 , qty1 AS qty, note1 AS note , admin FROM jobs
    UNION ALL
    SELECT id, 2 AS subid, `name`, date2 AS date1 , qty2 AS qty, note2 AS note , admin FROM jobs WHERE date2 <>''
    UNION ALL
    SELECT id, 3 AS subid, `name`, date3 AS date1 , qty3 AS qty, note3 AS note , admin FROM jobs WHERE date3 <> ''

    ) AS tabs
ORDER BY id,subid;

答案 1 :(得分:0)

为表格提供多个主键可能会更好。 如PRIMARY KEY(id,date)

CREATE TABLE notes (
  id INT NOT NULL AUTO_INCREMENT,
  name CHAR(30),
  date INT,
  qty INT,
  note CHAR(50),
  admin CHAR(10),
  PRIMARY KEY(id, date)
);

答案 2 :(得分:0)

您可以使用UNION ALL

来解决问题