SQL: Beyond INNER JOIN (for lack of a better title)
Environment:
- PHP 5.3.5 - Oracle 11g databaseTable Name: tips_categories
id category picture 1 a e.jpg 2 b f.jpg 3 c g.jpg
Table Name: tips
id tips_categories_id tip 1 3 This is a tip. 2 2 This is another tip. 3 1 This is yet another tip.
Desired result:
$array_name['tips'] [0] category => 开发者_如何学编程a picture => e.jpg tips [0] => This is yet another tip. [1] category => b picture => f.jpg tips [0] => This is another tip. [2] category => c picture => g.jpg tips [0] => This is a tip.
Writing one query that returns the desired resuilt is beyond my current knowledge of SQL. An INNER JOIN does not return the desired result. If it cannot be done in one query, I guess the following two queries will have to be used instead:
SELECT id,category,picture FROM tips_categories
SELECT tip FROM tips WHERE tips_categories_id = idI would greatly appreciate suggestions on how to write this query in one statement. Thank you :-)
Queries don't return hierarchical result sets. So what you are trying to do is impossible.
You can write a simple inner join query, order by id
, and then create the array your self iterating over the result set and adding a new entry into the array every time id
changes.
Query:
SELECT tips.id,category,picture, tip
FROM tips_categories
INNER JOIN tips on (tips_categories_id = id)
ORDER BY tips.ip
So, your result set will be something like:
id category picture tip
1 a e.jpg This is yet another tip A01.
1 a e.jpg This is yet another tip A02.
1 a e.jpg This is yet another tip A03.
2 b f.jpg This is another tip B01.
2 b f.jpg This is another tip B02.
3 c g.jpg This is a tip C01.
Provided you have more entries on your tips
table.
You iterate with PHP and produce the desired result on your array. It should be pretty simple and straightforward.
Well this:
SELECT c.id, c.category, c.picture, t.tip
FROM tips_categories AS c
INNER JOIN tips AS t
ON t.tips_categories_id = c.id
Certainly returns the data you want, but tip will simply be a 4th column, not some kind of hierarchy.
What are you using to build your array(s) from the results?
精彩评论