MySQL查询,无法弄清楚如何获取正确的数据

时间:2014-04-07 18:13:29

标签: mysql sql

这个查询与我曾尝试过的最复杂的问题接壤。

我的表格(我删除了无关的数据)

mysql> describe Posts;
+-----------+---------+------+-----+---------+----------------+
| Field     | Type    | Null | Key | Default | Extra          |
+-----------+---------+------+-----+---------+----------------+
| id        | int(11) | NO   | PRI | NULL    | auto_increment |
| Time      | int(11) | YES  | MUL | NULL    |                |
+-----------+---------+------+-----+---------+----------------+

mysql> describe Containers;
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| id       | int(11)     | NO   | PRI | NULL    | auto_increment |
| pid      | int(11)     | YES  | MUL | NULL    |                |
| iid      | int(11)     | YES  |     | NULL    |                |
+----------+-------------+------+-----+---------+----------------+

mysql> describe Images;
+--------------+--------------+------+-----+---------+----------------+
| Field        | Type         | Null | Key | Default | Extra          |
+--------------+--------------+------+-----+---------+----------------+
| id           | int(11)      | NO   | PRI | NULL    | auto_increment |
| LocalPath    | varchar(100) | YES  |     | NULL    |                |
| Category     | varchar(20)  | YES  |     | NULL    |                |
+--------------+--------------+------+-----+---------+----------------+

关系:

Posts.id> Containers.pid

Containers.iid> Images.id

我想:

获取相应Images.Category为value1,value2或value3之一的所有帖子。通过Posts.Time订购帖子。

伪代码:获取所有数据WHERE Images.Category IN(' value1',' value2,' value3')ORDER BY Posts.Time DESC。

尝试:

SELECT * FROM Images I
INNER JOIN Containers C ON C.iid = I.id
INNER JOIN Posts P ON C.pid = P.id
WHERE I.Category IN('value1','value2','value3'); 

结果:好的,但没有按Posts.Time排序帖子。

SELECT * FROM Posts P
INNER JOIN Containers C ON P.id = C.pid
RIGHT OUTER JOIN Images I ON C.iid = I.id
WHERE I.Category IN('value1','value2','value3')
ORDER BY P.Time DESC;

结果:获取不包含Images.Category的帖子行。

我希望我的问题格式正确,感谢您的时间。

1 个答案:

答案 0 :(得分:1)

试试这个:

 SELECT * FROM Images I
 INNER JOIN Containers C ON C.iid = I.id
 INNER JOIN Posts P ON C.pid = P.id
 WHERE I.Category IN('value1','value2','value3')
 ORDER BY P.Time DESC;