简体   繁体   English

从两个MySQL表中获取数据,并基于两个表中的数据进行ORDER

[英]Get data from two MySQL tables and ORDER based on the data from the two tables

I am lost trying to join two tables together and then returning the results ordered by columns in both tables. 我迷失了试图将两个表连接在一起,然后返回两个表中列排序的结果。 Here is the query i have that does not return any rows: 这是我不返回任何行的查询:

SELECT category.name,
       client.name,
       client.member
FROM   `category`,
       `client`
       INNER JOIN `client`
               ON client.name = category.name
WHERE  catdesc = '$info'
ORDER  BY client.member,
          category.name ASC  

What I want to return with this query: 我想通过此查询返回什么:

I want a list of names (name is common to both tables) that have a certain 'catdesc' ORDERED 我想要一个具有特定“ catdesc”顺序的名称列表(两个表的名称均相同)

FIRST: by members sorted by name ASC 第一:按会员名字(ASC)排序

THEN 然后

SECOND: after the members, the non-members sorted by name ASC. 第二:在成员之后,非成员按名称ASC排序。

Your join query is not correct you have 您的加入查询不正确

SELECT 
category.name, 
client.name, 
client.member 
FROM `category`,
`client` <----- here is the issue
INNER JOIN `client` ON client.name = category.name 
WHERE catdesc ='$info' 
ORDER BY client.member, category.name ASC

This should be 这应该是

SELECT 
category.name, 
client.name, 
client.member 
FROM `category`
INNER JOIN `client` ON client.name = category.name 
WHERE catdesc ='$info' 
ORDER BY client.member, category.name ASC

You have three table references in your query, at least one of the references to the client table needs to be given an alias, otherwise, you are going to have an "ambiguous column" error. 您的查询中有三个表引用,至少要对client表的引用之一赋予别名,否则,将出现“歧义列”错误。

Don't mix the old-school "comma" join operator with the JOIN keyword. 不要将老式的“逗号” JOIN运算符与JOIN关键字混合使用。 Best practice is to qualify all column references, even if they aren't ambiguous. 最佳实践是限定所有列引用,即使它们不是模棱两可的。

Your current query text is equivalent to: 您当前的查询文本等效于:

SELECT category.name
     , client.name
     , client.member
  FROM `category`
  JOIN `client`
  JOIN `client` 
    ON client.name = category.name
 WHERE catdesc ='$info' 
ORDER BY client.member, category.name ASC

Which we'd expect to throw an error. 我们希望抛出一个错误。 We'd really expect to see something more like: 我们真的希望看到更多类似的东西:

SELECT category.name
     , client.name
     , client.member
  FROM `category`
  JOIN `client`
    ON client.name = category.name
 WHERE category.catdesc = '$info'
 ORDER
    BY client.member
     , category.name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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