“复杂”的MySQL关系数据库查询

时间:2012-01-09 12:06:28

标签: mysql relational-database

我没有很多关系数据库的经验,而且我在这个问题上挣扎了一段时间但运气不好......

所以,我有几张桌子:

CREATE TABLE `shows` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `show_name` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
);

CREATE TABLE `playlists` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` int(11) NOT NULL,
  `time` int(11) NOT NULL,
  PRIMARY KEY (`id`)
);

CREATE TABLE `items` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
);

CREATE TABLE `items_playlists` (
  `item_id` int(11) NOT NULL,
  `playlist_id` int(11) NOT NULL,
  PRIMARY KEY (`item_id`,`playlist_id`),
  KEY `fk01` (`item_id`),
  KEY `fk02` (`playlist_id`)
);

CREATE TABLE `subtitles` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `line1` varchar(500) NOT NULL,
  `line2` varchar(500) NOT NULL,
  `line3` varchar(500) NOT NULL,
  PRIMARY KEY (`id`)
);

CREATE TABLE `items_subtitles` (
  `item_id` int(11) NOT NULL,
  `subtitle_id` int(11) NOT NULL,
  PRIMARY KEY (`item_id`,`subtitle_id`),
  KEY `fk01` (`item_id`),
  KEY `fk02` (`subtitle_id`)
);

CREATE TABLE `subtitles_txt` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `subtitle_text` varchar(500) NOT NULL,
  PRIMARY KEY `id` (`id`)
);

playlists.name实际上是对shows.id值的引用。

subtitles.line1subtitles.line2subtitles.line3分别对应subtitles_txt.id

我需要的是根据subtitles_txt.subtitle_text值获取所有表中的所有行,条件是值在右侧有一个通配符(...WHERE subtitle_text LIKE 'value%')。

我认为不幸的是我无法更改表结构,因为这是一些大型项目的一部分,而其他许多东西依赖于其中的一些表,所以我应该从中做出一些疑问......

1 个答案:

答案 0 :(得分:0)

呃,不知怎的,我设法检索了我需要的数据,但我不确定这是否是一个好方法,所以如果我在这里犯了一些小错误或者查询可以某种方式'简化',请纠正我。谢谢:))

SELECT st.line1, st.line2, st.line3, ii.title, pp.name, pp.time, ss.show_name, stxt.subtitle_text, stxt2.subtitle_text, stxt3.subtitle_text 

FROM subtitles st

LEFT JOIN items_subtitles iss ON iss.subtitle_id = st.id
LEFT JOIN items ii ON iss.item_id = ii.id
LEFT JOIN items_playlists ipp ON ipp.item_id = ii.id
LEFT JOIN playlists pp ON ipp.playlist_id = pp.id
LEFT JOIN shows ss ON pp.name = ss.id
LEFT JOIN subtitles_txt stxt ON st.line1 = stxt.id
LEFT JOIN subtitles_txt stxt2 ON st.line2 = stxt2.id
LEFT JOIN subtitles_txt stxt3 ON st.line3 = stxt3.id

WHERE st.line1 = ANY (SELECT id FROM subtitles_txt WHERE subtitle_text LIKE 'some_query%')
OR st.line2 = ANY (SELECT id FROM subtitles_txt WHERE subtitle_text LIKE 'some_query%')
OR st.line3 = ANY (SELECT id FROM subtitles_txt WHERE subtitle_text LIKE 'some_query%')