简体   繁体   中英

MySQL query, can't figure out how to fetch the correct data

This query borders on the most complex one I've ever attempted.

My tables: (I removed irrelevant data)

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    |                |
+--------------+--------------+------+-----+---------+----------------+

Relations:

Posts.id > Containers.pid

Containers.iid > Images.id

I want to:

Get all Posts where the corresponding Images.Category is one of value1, value2 or value3. Order Posts by Posts.Time.

Pseudo-code: Fetch all data WHERE Images.Category IN('value1','value2,'value3') ORDER BY Posts.Time DESC.

Attempts:

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'); 

Result: Ok, but not getting the Posts sorted by 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;

Result: Getting lines for Posts which does not contain Images.Category.

I hope my question is properly formatted, I appreciate your time.

try this:

 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM