简体   繁体   中英

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

FIRST: by members sorted by name ASC

THEN

SECOND: after the members, the non-members sorted by name 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.

Don't mix the old-school "comma" join operator with the JOIN keyword. 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

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