[英]MySQL Joins and ORDER BY in PHP / MYSQL
I have a database that looks like this with two tables 我有一个带有两个表的数据库
Items id | Title ----------------------------- 1 Bus 2 Plane 3 Jet 4 Shoes 5 Chair
Sorting id | CatID | ItemID | SortOrder ------------------------------------------------------------------------------- 1 3 3 3 2 3 2 1 3 3 4 2 4 3 1 0 5 4 5 4
I can't figure out how to list the Titles of the ITEMS table based on the "SortOrder" Column of the SORTING table. 我无法弄清楚如何列表中的项目表的基础上, 分类表的“SortOrder的”列标题。
Here is what I tried so far: 这是我到目前为止尝试过的:
SELECT *
FROM Items
LEFT JOIN Sorting ON Items.id = Sorting.ItemID
WHERE Sorting.CatID = 3
ORDER BY Sorting.SortOrder
I'm not sure what I'm doing wrong 我不确定自己在做什么错
EDIT 编辑
It looks like the MySQL query is correct, the problem is happening because when I output the $row['id'] of the Items Table it is incorrect. 看来MySQL查询是正确的,正在发生问题,因为当我输出Items表的$ row ['id']时,它是不正确的。 I have an Ajax PHP update that is updating the database based on the id of an li tag. 我有一个Ajax PHP更新,它根据li标签的ID更新数据库。
Any ideas why the $row['id'] is outputting incorrectly? 有什么想法为什么$ row ['id']输出错误? I think it has something to do with the Items.id = Sorting.ItemID 我认为这与Items.id = Sorting.ItemID有关
This works as expected - SQLFiddle DEMO : 这按预期方式工作-SQLFiddle DEMO :
SELECT i.*, s.SortOrder
FROM items i, sorting s
WHERE i.id = s.ItemID
AND s.CatID = 3
ORDER BY s.SortOrder
Try 尝试
SELECT *
FROM Items
LEFT JOIN Sorting ON Items.id = Sorting.ItemID
WHERE Sorting.CatID = 3
ORDER BY Sorting.SortOrder ASC
add DESC
or ASC
in ORDER BY
clause. 在ORDER BY
子句中添加DESC
或ASC
。
if you use ASC
then sorted result will be 0 1 2 3 4
for SortOrder
. 如果使用ASC
则SortOrder
排序结果将为0 1 2 3 4
。
sample php code to get title 示例php代码获取标题
<?php
$query = mysqli_query(above_query)or die(mysqli_error());
while($result = mysqli_fetch_assoc($query))
{
echo $result['title']. '<br/>';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.